gpt4 book ai didi

iphone - UITableView 中的默认 list

转载 作者:行者123 更新时间:2023-11-28 22:49:02 25 4
gpt4 key购买 nike

我想在 UITableView 中为单个选择实现 list 。另外,我需要默认选择一个单元格。这是我在 cellForRowAtIndexPath 中的实现:

NSUInteger row = [indexPath row];
NSUInteger oldRow = [lastIndexPath row];
cell.accessoryType = (row == oldRow && lastIndexPath != nil) ? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone;

if (indexPath.row == selectedRow ) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else {
cell.accessoryType = UITableViewCellAccessoryNone;
}

didSelectRowAtIndexPath 有这段代码:

if (!self.lastIndexPath) {
self.lastIndexPath = indexPath;
}

if ([self.lastIndexPath row] != [indexPath row])
{
UITableViewCell *newCell = [tableView cellForRowAtIndexPath: indexPath];
newCell.accessoryType = UITableViewCellAccessoryCheckmark;

UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:self.lastIndexPath];
oldCell.accessoryType = UITableViewCellAccessoryNone;

self.lastIndexPath = indexPath;
}
else {
UITableViewCell *newCell = [tableView cellForRowAtIndexPath: indexPath];
newCell.accessoryType = UITableViewCellAccessoryCheckmark;
}

使用这段代码我可以获得默认的复选标记,但是每当我选择另一行时第一个保持选中状态,直到我不单击该单元格。那么,如果我想选择我想要的结果,我应该怎么做?

`

最佳答案

我觉得代码有点太复杂了。您只需要一个属性:

NSInteger _selectedRow;

这在最初定义时将提供一个默认的选定行。并且它还将保持之前的选择(在查找要“取消选择”的单元格时):

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CELL_IDENTIFIER];

if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CELL_IDENTIFIER];
}

if ([indexPath row] == _selectedRow) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}

cell.textLabel.text = [NSString stringWithFormat:@"Row %d", indexPath.row];

return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (_selectedRow >= 0) {
[tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:_selectedRow inSection:0]].accessoryType = UITableViewCellAccessoryNone;
}
_selectedRow = [indexPath row];
[tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;

[tableView deselectRowAtIndexPath:indexPath animated:YES];
}

创建此 View 时,如果您分配:

_selectedRow = 1;

然后第二行会自动被选中。 -1 的值表示没有默认选择,上述两种方法将自动添加/删除点击行的复选标记。

关于iphone - UITableView 中的默认 list ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12412649/

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