如何在 Objective-c 中的自定义 UITableViewCell 中更改 UIButon 文本属性



我看过很多关于这个主题的帖子,但我找不到适合解决我确切情况的帖子。我有一个UITableView,其中包含一个带有UIButton和UITextfield的自定义UITableViewCell。我可以在我的 UITableView 委托中使用以下代码抓住按钮按下:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   static NSString *simpleTableIdentifier = @"ConversationCell";
    ConversationCell *cell = (ConversationCell *)[tableView   dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil)
    {
       NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"ConversationCell" owner:self options:nil];
       cell = [nib objectAtIndex:0];
    }
    [cell.participantBtn addTarget:self action:@selector(editClickedParticipant:) forControlEvents:UIControlEventTouchUpInside];
   return cell;
}

然后添加以下方法来处理点击

- (void) editClickedParticipant:(id) sender
{
    ...
}

在editClickedParticipant 中,我显示了一个带有选项列表的UIPickerView。选择选取器中的索引后,如何更改触发 editClickedParticipant 操作的单元格中的按钮文本属性?有没有办法使用标签或其他东西?

这可以使用tag属性轻松完成:

cell.participantBtn.tag = indexPath.row; // This goes in cellForRowAIndexPath method

- (void) editClickedParticipant:(id) sender {
   NSInteger row = sender.tag; //Anything can be done with the button
   NSIndexPath *indexPath = [NSIndexPath indexPathForItem: row inSection:0];
   //Change your button's text attribute here below
   [sender setTitle:@"Your new title" forState:UIControlStateNormal];
}

您可以使用以下方法获取按钮:

UIButton *senderButton = (UIButton *)sender;

并在发件人按钮中应用更改。

或如果您需要单元格,

- (void) editClickedParticipant:(id) sender {
   CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
//You can get the cell and other components inside the cell using indexPath
}

尝试在视图控制器生命周期方法中应用按钮文本中的更改tableView:willDisplayCell:forRowAtIndexPath:

这是视图控制器生命周期中调整单元格内视图的适当位置/时间 - 就在显示之前。

- (void)tableView:(UITableView *)tableView 
  willDisplayCell:(UITableViewCell *)cell 
forRowAtIndexPath:(NSIndexPath *)indexPath {
    'for example...
    cell.participantBtn.label = "new label";
}

从苹果文档中...

此方法使委托有机会重写基于状态 表视图之前设置的属性,例如选择和 背景颜色。委托返回后,表视图仅设置 alpha 和帧属性,然后仅在将行作为 他们滑入或滑出。

最新更新