0

我想在表格视图中创建一个简单的复选框。首先,我在情节提要中创建视图,每个元素在单元格中都有一个标签。然后我在 Controller.m 中编码

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ...
    UIButton  *checkbox = (UIButton *)[cell viewWithTag:103];
    checkbox.selected = NO;

    [checkbox setBackgroundImage:[UIImage imageNamed:@"uCheckbox2px"] forState:UIControlStateNormal];

    [checkbox addTarget:self action:@selector(changeState:) forControlEvents:UIControlEventTouchUpInside];
    ...
}

-(void) changeState:(UIButton *)checkbox
{

    checkbox.selected = !checkbox.selected;
    if (checkbox.selected)
        [checkbox setBackgroundImage:[UIImage imageNamed:@"cCheckbox2px"] forState:UIControlStateSelected];
    else
       [checkbox setBackgroundImage:[UIImage imageNamed:@"uCheckbox2px"] forState:UIControlStateNormal];

}

但是,如果我点击按钮,图像不会改变。为什么会这样,我该如何解决?感谢帮助!

4

3 回答 3

1

让它像这样

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ...
    UIButton  *checkbox = (UIButton *)[cell viewWithTag:103];

    [checkbox setBackgroundImage:[UIImage imageNamed:@"uCheckbox2px"] forState:UIControlStateNormal];
    [checkbox setBackgroundImage:[UIImage imageNamed:@"cCheckbox2px"] forState:UIControlStateSelected];

    [checkbox addTarget:self action:@selector(changeState:) forControlEvents:UIControlEventTouchUpInside];
    ...
}

-(void) changeState:(UIButton *)checkbox
{

    checkbox.selected = !checkbox.selected;
}
于 2013-11-05T11:12:54.490 回答
1

这是因为每次调用cellForRowAtIndexPath: checkbox.selected = NO;都会使选定的属性FALSE。所以在那之后,在 changeState:中,

checkbox.selected = !checkbox.selected;

会将 selected 属性更改为TRUE。因此,每当您点击按钮时,所选属性仅变为TRUE。所以移动checkbox.selected = NO; if(cell == nil)条件内

于 2013-11-05T11:10:44.933 回答
0

我猜你在按钮点击事件中给出的代码是不需要的。只改变状态就足够了。

    if (checkbox.selected)
        [checkbox setBackgroundImage:[UIImage imageNamed:@"cCheckbox2px"] forState:UIControlStateSelected];
    else
       [checkbox setBackgroundImage:[UIImage imageNamed:@"uCheckbox2px"] forState:UIControlStateNormal];

UIControlStateSelected但是您需要UIControlStateNormalcellForRowAtIndexPath.

于 2013-11-05T11:08:58.957 回答