大家好,
我正在尝试添加带有与 indexPath.row 相关的标签的自定义按钮。如果我不将新行插入到 TableView 中,我可以正确查看标记值。但是,当我插入新行时,如果插入的行不在 0 到 9 之间(iphone 5 可以显示),我的新行标签值不正确。在 iPhone 上,我需要向下滚动才能看到。
但是,使用相同的代码,我可以在我的 ipad 上正确获取我的标签值。我不需要在我的 iPad 上向下滚动表格 View 来查看我的所有行。我想知道为什么会发生以及如何解决。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"dialoguesTableCell";
dialoguesCell *cell = [tableViewdequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[dialoguesCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
UIButton *yourButton = [UIButton buttonWithType:UIButtonTypeCustom];
[yourButton setImage:[UIImage imageNamed:@"1StarBlank.png"] forState:UIControlStateNormal];
[yourButton setTitle:@"Button" forState:UIControlStateNormal];
[yourButton addTarget:self action:@selector(buttonSelected:) forControlEvents:UIControlEventTouchUpInside];
yourButton.tag=indexPath.row;
yourButton.frame = CGRectMake(5, 10, 40, 25);
[cell addSubview:yourButton];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSIndexPath *indexPathstoinsert = [NSIndexPath indexPathForRow:indexPath.row+1 inSection:section];
NSArray *indexPathsToInsertArray = [NSArray arrayWithObject:indexPathstoinsert];
[[self mainTableView] insertRowsAtIndexPaths:indexPathsToInsertArray withRowAnimation:UITableViewRowAnimationRight];
}
最佳答案
这不能正常工作,因为 UITableView 重用单元格
当您向下滚动时,第一个单元格不再可见并被重复使用。
如果表格..“小”,您可以通过不重复使用单元格
来解决它
但是如果表格不是只有几个条目而是大量数据,您真的想改变您的方式
为按钮分配标签:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
例如
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
UIButton *b = nil;
for(UIView *v in cell.subviews) {
if([v isKindOfClass:[UIButton class]]) {
b = (UIButton*)v;
break;
}
}
b.tag = indePath.row;
}
在评论中您提到了另一个问题:按钮隐藏在您的 didSelectRow
方法中,然后在滚动后也从其他单元格中消失。同样的问题:单元格对象被 TableView 重用。不要将状态存储在可重复使用的单元格中!
取而代之的是有一个记住状态的“模型”树或数组:文本、图像、标签、隐藏:是/否
NSArray *myTableContents
NSMutableDictionary *d1 = [@{@"text:@"bla", @"hidden":@NO} mutableCopy];
NSMutableDictionary *d2 = [@{@"text:@"bloo", @"hidden":@NO} mutableCopy];
NSMutableDictionary *d3 = [@{@"text:@"foo", @"hidden":@NO} mutableCopy];
myTableContents = @[d1,d2,d3];
然后始终在 numberOfRows 和 viewForRow 中使用该数组并在 didSelectEntry 中修改它
关于ios - 在带有标签的 TableView 中添加自定义按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14008831/