繁体   English   中英

UiButton文本不会在Tableview单元格中保持更改

[英]UiButton text wont stay changed in Tableview cell

我在网上搜索了所有内容,但似乎找不到解决此简单问题的方法。 当工作“喜欢”时,我有一个按钮的表格视图。 当按下按钮时,它将单词更改为“不喜欢”。 我可以使用它,但是当我向下滚动表格时,我看到其他按钮也更改为“不喜欢”,有时还会与“喜欢”重叠。 当我向上滚动时,我选择的原始按钮将恢复为正常状态。 我了解这些单元是可重用的,这就是为什么我在数据源中使用可变数组而仍然无法正常工作的原因。 请帮忙!

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"SimpleTableCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }
    UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [myButton setTitle:@"Like" forState:UIControlStateNormal];
    myButton addTarget:self action:@selector(tapped:) forControlEvents:UIControlEventTouchUpInside];
    myButton.frame = CGRectMake(14.0, 10.0, 125.0, 25.0);
    myButton.tag =indexPath.row;
    [cell.contentView addSubview:myButton];
    cell.textLabel.text = [recipes objectAtIndex:indexPath.row];  
 return cell;
}

动作方法:

-(void)tapped:(id)sender {
    UIButton *senderButton = (UIButton *)sender;

    UITableViewCell *parentCell = [[sender superview]superview];

    NSIndexPath *indexPathLiked = [table indexPathForCell:parentCell];

    [array replaceObjectAtIndex:senderButton.tag withObject:[NSNumber numberWithInt:1]];

    [sender setTitle:@"Unlike" forState:UIControlStateNormal];

}

如果表调用cellForRowAtIndexPath,则始终创建一个新按钮。 当您得到一个可重复使用的单元格时,该按钮仍然存在,然后将一个新的单元格放在该按钮上。

将您的方法更改为:

if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [myButton setTitle:@"Like" forState:UIControlStateNormal];
    myButton addTarget:self action:@selector(tapped:) forControlEvents:UIControlEventTouchUpInside];
    myButton.frame = CGRectMake(14.0, 10.0, 125.0, 25.0);
    myButton.tag =indexPath.row;
    [cell.contentView addSubview:myButton];
}
else {
   // todo: change the button title to "like" or "unliked" value
}
cell.textLabel.text = [recipes objectAtIndex:indexPath.row];  

PS:这没有意义,您不使用它,为什么要这样做?

UITableViewCell *parentCell = [[sender superview]superview];
NSIndexPath *indexPathLiked = [table indexPathForCell:parentCell];

如果只有一个部分,则无需使用superview就可以获取单元格:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:sender.tag inSection:0]
UITableViewCell *parentCell = [table cellForRowAtIndexPath:indexPath];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM