![](/img/trans.png)
[英]how to set custom UILabel text on UITableView prototype cell
[英]set uilabel's text that added in uitableview cell
在每個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的文本? 謝謝。
@"0"
硬編碼為標簽的文本? 如果您的目標是跟蹤投票,則需要在某些數據結構中跟蹤當前的投票計數。 然后,根據數據中的實際值設置每個單元格。 然后,在點擊按鈕時可以更新此數據。 indexPath.row
按鈕的標記設置為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];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.