我想知道如何将切换功能添加到UIButton
中,就像用户点击未选择的按钮一样,该按钮变为选中状态并保持选中状态,直到用户通过像以前一样使未选中状态再次点击它为止。
我正在考虑制作一个IBAction
,将其从未选中更改为选中,我该怎么做?
这是我尝试过的:
-(IBAction)toggle {
//Toggle on implementation.
button.selected = YES;
button.highlighted = NO;
button.enabled = YES;
//Toggle off implementation.
if (button.highlighted == YES) {
button.selected = NO;
button.highlighted = YES;
button.enabled = NO;
}
}
问题...
-(IBAction)toggleFav {
if (favButton == nil) {
UIImage *unselectedImage = [UIImage imageNamed:@"favUntapped.png"];
UIImage *selectedImage = [UIImage imageNamed:@"favTapped.png"];
[favButton setImage:unselectedImage forState:UIControlStateNormal];
[favButton setImage:selectedImage forState:UIControlStateSelected];
[favButton setFrame:CGRectMake(0, 0, 40, 40)];
}
if([favButton isSelected]){
//Add to menu.
[favButton setSelected:NO];
} else {
//Remove from menu.
[favButton setSelected:YES];
}
}
最佳答案
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
UIImage *unselectedImage = [UIImage imageNamed:@"unselected.png"];
UIImage *selectedImage = [UIImage imageNamed:@"selected.png"];
UIButton *b = [UIButton buttonWithType:UIButtonTypeCustom];
[b setBackgroundImage:unselectedImage forState:UIControlStateNormal];
[b setBackgroundImage:selectedImage forState:UIControlStateSelected];
[b addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[b setFrame:CGRectMake(0, 0, 40, 40)];
[cell.contentView addSubview:b];
}
return cell;
}
-(void) buttonPressed:(UIButton *)sender
{
if([sender isSelected]){
//...
[sender setSelected:NO];
} else {
//...
[sender setSelected:YES];
}
}
您的
toggleFav
代码没有多大意义。if (favButton == nil) {
检查是否存在favButton
。但是,如果您要与IB进行连接,那它应该一直在那儿。如果不是,按钮怎么会调用此方法?所以这样做:-(void)viewDidLoad
{
//....
UIImage *unselectedImage = [UIImage imageNamed:@"favUntapped.png"];
UIImage *selectedImage = [UIImage imageNamed:@"favTapped.png"];
[favButton setImage:unselectedImage forState:UIControlStateNormal];
[favButton setImage:selectedImage forState:UIControlStateSelected];
[favButton setFrame:CGRectMake(0, 0, 40, 40)];
//....
}
-(IBAction)toggleFav:(UIButton *)sender {
if([sender isSelected]){
//...
[sender setSelected:NO];
} else {
//...
[sender setSelected:YES];
}
}
Here,您将找到一个带有DetaiView的示例项目,其中包含一个带有2个状态的Button。
注意:我正在保存在NSUserDefaults中选择了哪个按钮的信息。你不应该那样做。相反,您需要将其保存在模型中。但是由于我没有关于您的模型的信息,因此我仅使用NSUserDefaults。
关于objective-c - 在UIButton中实现切换功能,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4208364/