1

这是我的代码

- (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];
}
}
4

2 回答 2

0

首先在 ViewDidLoad 中为两种状态(UIControlStateNormal,UIControlStateSelected)设置按钮图像,然后执行 [cell.btnSelect setSelected:YES]; 或 [cell.btnSelect setSelected:NO]; 根据要求。

否则在点击按钮时更改 UIControlStateNormal 的图像。

于 2015-12-30T12:13:37.367 回答
-1

每次标题加载时您都在创建 UIButton,这会导致您的按钮重置,一种方法是在 storyborad 或 xib 中设计单元格并使用参考,还有一个 DataSource 来跟踪值,例如

 if([dataSouce containsObject:yourItem]){
        //selected button image
        [cell.btnSelect setSelected:YES];
    }
    else{
        //unselected button image

        [cell.btnSelect setSelected:NO];

    }
于 2015-12-30T11:56:08.770 回答