【问题标题】:set uilabel's text that added in uitableview cell设置在 uitableview 单元格中添加的 uilabel 的文本
【发布时间】:2014-07-06 16:55:50
【问题描述】:

在每个uitableview单元格中,有一个按钮,一个uilabel,如以下代码

ListCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[ListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}


[cell.UIButton addTarget:self action:@selector(ButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
cell.UIButton.tag = indexPath.row;
cell.UILabel.text = @"0";

我想要这个,当我点击按钮时,与uibutton在同一单元格的uilabel.text会添加一个,我再次点击,uilabel.text会添加一个,就像投票一样。

- (IBAction)ButtonClicked:(UIButton *)sender
{
  NSInteger selectedRow = sender.tag;
}

那么如何更改 uilabel 的文本?谢谢。

【问题讨论】:

标签: ios objective-c uitableview uibutton uilabel


【解决方案1】:
  1. 为什么要将字符串@"0" 硬编码为标签文本?如果您的目标是跟踪投票,则需要在某些数据结构中跟踪当前投票计数。然后根据数据的实际值设置每个单元格。然后可以在点击按钮时更新此数据。
  2. 如果可以添加、删除或移动行,将按钮的标签设置为indexPath.row 会导致很多问题。有一种更好的方法可以从按钮中获取单元格,而无需使用标签。

以下假设您的班级中有一个 NSMutableArray ivar (_votes) 作为投票计数的数据源。

现在您的cellForRowAtIndexPath 变为:

ListCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[ListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    [cell.UIButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
}

NSNumber *votes = _votes[indexPath.row];    
cell.UILabel.text = [NSString stringWithFormat:@"%@", votes];

您的按钮操作变为:

- (void)buttonClicked:(UIButton *)button {
    CGPoint pointInTable = [button convertPoint:CGPointMake(5, 5) toView:self.tableView];
    NSIndexPath *path = [self.table indexPathForRowAtPoint:pointInTable];

    NSNumber *oldVote = _votes[path.row];
    NSNumber *newVote = @([oldVote intValue] + 1);
    _votes[path.row] = newVote;

    [self.tableView reloadRowsAtIndexPaths:@[ path ] withRowAnimation: UITableViewRowAnimationFade];
}

【讨论】:

  • 谢谢,我更新了代码,解决了这个问题。
猜你喜欢
  • 2015-12-16
  • 1970-01-01
  • 2011-10-17
  • 1970-01-01
  • 2013-11-28
  • 1970-01-01
  • 1970-01-01
  • 2011-12-27
  • 2018-04-12
相关资源
最近更新 更多