jym*_*man 1 uibutton uitableview ios xcode-storyboard
我在 UITableViewCell 中的 UIButton 有一些问题。我使用原型单元格在情节提要中创建了一个自定义 tableviewcell。有两个按钮,我为它们设置了标签。第一次绘制表格视图时,一切都显示正确,但是如果我滚动或更新数据并在 tableview 上调用 reloadData,它不会正确更新。
代码:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Moment Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSLog(@"Cell: %@", cell);
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
NSArray *row = [mMoment objectAtIndex:indexPath.row];
UILabel *label;
label = (UILabel *)[cell viewWithTag:101];
label.text = [row objectAtIndex:0];
label = (UILabel *)[cell viewWithTag:102];
label.text = [NSString stringWithFormat:@"Koeff: %@",[row objectAtIndex:2]];
UIButton *button;
NSString *btn_title;
button = (UIButton *)[cell viewWithTag:104];
NSLog(@"Button: %@", button);
[button setTag:1];
btn_title = [NSString stringWithFormat:@"%@", [row objectAtIndex:4]];
[button setTitle:btn_title forState:(UIControlState)UIControlStateNormal];
[button addTarget:self action:@selector(poangButtonClick:event:) forControlEvents:UIControlEventTouchUpInside];
NSLog(@"Row: %d, Poäng: %@", indexPath.row, btn_title);
label = (UILabel *)[cell viewWithTag:103];
label.text = btn_title;
button = (UIButton *)[cell viewWithTag:105];
[button setTag:2];
btn_title = [NSString stringWithFormat:@"%@", [row objectAtIndex:5]];
[button setTitle:btn_title forState:(UIControlState)UIControlStateNormal];
[button addTarget:self action:@selector(poangButtonClick:event:) forControlEvents:UIControlEventTouchUpInside];
return cell;
Run Code Online (Sandbox Code Playgroud)
}
第一次button = (UIButton *)[cell viewWithTag:104];在每个可见行上调用,一切都是正确的,但是如果我滚动或重新加载视图,按钮为零?为什么?以相同的方式检索标签并正确显示。如何更改单元格中按钮的标签?
问候
/弗雷德里克
快速猜测:我看到您正在重置用于引用它的按钮“标签”值。所以你不能再用值 104 检索它(在改变它之后)(在第一次创建之后它现在是 1 和 2)
[button setTag:1];
Run Code Online (Sandbox Code Playgroud)
所以,你下次不会通过
button = (UIButton *)[cell viewWithTag:105];
Run Code Online (Sandbox Code Playgroud)
我的假设是单元格不会被释放,因此这个标签值保持不变。也许这会解决它。