DSh*_*hah 0 iphone objective-c uitableview ios
下面是代码UITableView,但当我滚动它的行为奇怪(太烦人)...这个问题是由于reuseIdentifier ....但不知道如何解决..
- (UITableViewCell *)tableView:(UITableView *)tableView1 cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView1 dequeueReusableCellWithIdentifier:CellIdentifier];
NSInteger imgTag = 1;
NSInteger lblTag = 2;
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(2, 2, 52, 52)];
// Image:[UIImage imageNamed:[self.glassType objectAtIndex:indexPath.row]]];
imgView.tag = imgTag;
[cell.contentView addSubview:imgView];
[imgView release];
UILabel *lblName = [[UILabel alloc] initWithFrame:CGRectMake(60, cell.frame.size.height/4, 200, 21)];
// lblName.text = [self.glassName objectAtIndex:indexPath.row];
lblName.tag = lblTag;
[cell addSubview:lblName];
[lblName release];
}
NSInteger imgIndex = 2;
NSInteger lblIndex = 3;
((UIImageView *)[cell viewWithTag:imgTag]).image = [[self.glassType objectAtIndex:indexPath.row] objectAtIndex:imgIndex];
((UILabel *)[cell viewWithTag:lblTag]).text = [[self.glassName objectAtIndex:indexPath.row] objectAtIndex:lblIndex];
return cell;
}
- (void)tableView:(UITableView *)tableView1 didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView1 cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
Run Code Online (Sandbox Code Playgroud)
如何在索引处为行创建单元格,以便即使滚动时也保持不变?另外如何在UITableView??中进行单一选择?
答案是你不应该在"if(cell == nil){..."子句之外的表格单元格中添加子视图,或者在重新使用时将它们反复添加到同一个单元格中.
有关更详细的说明,请参阅我对此问题的回答,包括如何解决此问题的代码:
您也无法在表格单元格中存储状态,因为只要它们在屏幕外滚动,它们就会被回收并重新显示在表格中的不同索引处.您需要设置一个模型对象数组来存储表格单元格的状态(例如它们的附件类型应该是什么).在我对这个问题的回答中可以找到更详细的解释:
循环通过UITableView的UITableViewCells
如果您修复了如何将子视图添加到单元格中,并将"勾选"状态存储在模型对象数组中以及设置cell.accessoryType(以便在单元格出列时可以恢复它),那么您的方法行选择是正确的.
所以把它放在你的tableView:cellForRowAtIndexPath:方法中,就在之前return cell;:
MyModelObject *object = [self.arrayOfModelObjects objectAtIndex:indexPath.row];
BOOL isChecked = object.checked;
cell.accessoryType = isChecked? UITableViewCellAccessoryCheckmark: UITableViewCellAccessoryNone;
Run Code Online (Sandbox Code Playgroud)
在您的tableView: didSelectRowAtIndexPath:方法中,摆脱当前的逻辑并将其替换为:
- (void)tableView:(UITableView *)tableView1 didSelectRowAtIndexPath:(NSIndexPath *)indexPath
for (int i = 0; i < [self.arrayOfModelObjects count]; i++)
{
MyModelObject *object = [self.arrayOfModelObjects objectAtIndex:i];
object.checked = (i == indexPath.row); // only check the one we just tapped
}
//refresh table to update the accessory views for all rows
[tableView1 reloadData];
}
Run Code Online (Sandbox Code Playgroud)
显然arrayOfModelObjects用你自己的模型实现替换.如果您不想为此目的创建自定义类,则可以使用包含bool的NSNumber对象数组.
| 归档时间: |
|
| 查看次数: |
2646 次 |
| 最近记录: |