这是我的代码
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setImage:[UIImage imageNamed:@"Add_plus_iCon_iphone_4s"] forState:UIControlStateNormal];
button.frame = CGRectMake(sectionView.frame.size.width-10, 10, 20, 20);
[button addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
[sectionView addSubview:button];
}
- (void)btnAction:(UIButton *)sender
{
int i = [sender.titleLabel.text intValue];
NSNumber *numb;
if(i == 0)
{
numb = [NSNumber numberWithBool:NO];
sender.titleLabel.text = @"1";
[sender setImage:[UIImage imageNamed:@"Add_minus_iCon_iphone_4s"] forState:UIControlStateNormal];
[sender setImage:[UIImage imageNamed:@"Add_plus_iCon_iphone_4s"] forState:UIControlStateHighlighted];
}
else
{
numb = [NSNumber numberWithBool:YES];
sender.titleLabel.text = @"0";
[sender setImage:[UIImage imageNamed:@"Add_plus_iCon_iphone_4s"] forState:UIControlStateNormal];
[sender setImage:[UIImage imageNamed:@"Add_minus_iCon_iphone_4s"] forState:UIControlStateHighlighted];
}
}
答案 0 :(得分:0)
首先在ViewDidLoad中设置状态(UIControlStateNormal,UIControlStateSelected)按钮的图像,然后执行[cell.btnSelect setSelected:YES];或[cell.btnSelect setSelected:NO];根据要求。
否则在点击按钮时更改UIControlStateNormal的图像。
答案 1 :(得分:-1)
每次标题加载时都会创建UIButton,导致按钮重置, 1种方法是在storyborad或xib中设计单元格并使用引用, 还有一个DataSource来跟踪值 e.g。
if([dataSouce containsObject:yourItem]){
//selected button image
[cell.btnSelect setSelected:YES];
}
else{
//unselected button image
[cell.btnSelect setSelected:NO];
}