gpt4 book ai didi

iphone - UITable 为我的最后一行 UITableViewCell 加载第一个 UITableViewCell

转载 作者:行者123 更新时间:2023-12-03 21:19:54 42 4
gpt4 key购买 nike

在使用 UITableView 编码时,我遇到了这个我无法理解的错误。我的表格有 3 行,每行设置 50 像素,但第二行除外,我将其设置为 500 像素,它填满整个屏幕。当我向下滚动到底部时,问题出现了,我的底部角色是重复第一行外观。这是我的自定义代码:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return 3;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"TestTable";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

if (indexPath.section ==0 && indexPath.row==0) {
cell.contentView.backgroundColor = [UIColor redColor];
}
if (indexPath.section ==0 && indexPath.row==1) {
cell.contentView.backgroundColor = [UIColor blueColor];
}
if (indexPath.section ==0 && indexPath.row==2) {
cell.contentView.backgroundColor = [UIColor greenColor];
}


}
// Configure the cell...
return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row==1) {
return 400;
}
return 50;
}

根据代码,第一行是红色,第二行是红色,第三行是蓝色。但我的最后一行是红色(重复第一行)。如果我将第二行设置为比屏幕短,例如100px,第三行加载良好。

原始显示

enter image description here

向下滚动后

enter image description here

感谢各种建议,因为我已经不知道这是怎么发生的了。

谢谢

最佳答案

当第二行很长时,第一行变得不可见,并且其单元格在最后一行中重复使用。这就是为什么您应该在每次调用 tableView:cellForRowAtIndexPath: 时配置单元格,即在 if (cell == nil) {...} block 之后:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"TestTable";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}

// Configure the cell...
if (indexPath.section == 0 && indexPath.row==0) {
cell.contentView.backgroundColor = [UIColor redColor];
}
if (indexPath.section ==0 && indexPath.row==1) {
cell.contentView.backgroundColor = [UIColor blueColor];
}
if (indexPath.section ==0 && indexPath.row==2) {
cell.contentView.backgroundColor = [UIColor greenColor];
}

return cell;
}

关于iphone - UITable 为我的最后一行 UITableViewCell 加载第一个 UITableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5769275/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com