【问题标题】:Highlight selected tableViewCell to match with UITextfield.text突出显示选定的 uitableViewCell 以与 UITextfield.text 匹配
【发布时间】:2023-03-07 18:36:01
【问题描述】:

我有一个表视图,其值可能相同。

选择单元格时,文本字段值将填充所选单元格。

我只想突出显示选择的行,而不是突出显示与文本字段相同的所有值。

我目前的做法:

data 是一个可能值的数组

if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
    reuseIdentifier:@"identifierCell"];
}

NSString *value = ([self.data objectAtIndex:indexPath.row]);
NSString *selectedValue = textField.text;

if ([value floatValue] == [selectedValue floatValue]) {
    cell.backgroundColor = [UIColor colorWithRed:220.0/255.0 green:220.0/255.0 blue:220.0/255.0 alpha:1.0];
    cell.textLabel.textColor = [UIColor whiteColor];
}
else {
    cell.backgroundColor = [UIColor clearColor];
    cell.textLabel.textColor = [UIColor blackColor];
}

旁注:我有几个这样的下拉字段,可以根据选择的行更改文本字段文本。 (即,如果在另一个下拉列表中选择了第 1 行,则 1.391 将填充到文本字段文本中。

不确定这会有多相关。

如何只检查被选中的行并根据下图填充文本字段?

更新:感谢@k06a,使用 indexPath 向前迈进了一步,但是现在出现的问题是,如果选择了行 A,B 的 indexPath 不应该改变。我正在考虑设置 2 个不同的 indexPath 变量,并且在 didSelectRowAt 上只为我调用的方法设置这些变量以更改其他相应的值

【问题讨论】:

  • 您可以通过UITableViews allowsMultipleSelection属性实现多个单元格选择。

标签: ios objective-c uitableview


【解决方案1】:

您可以枚举循环中的所有单元格,以根据selectedValue 和value 相等来选择和取消选择行。此循环将取消选择上一行,并选择一个新行。并且不要忘记在对可重用单元进行出队后设置初始状态。所有单元格都可以通过以下方式获取:self.tableView.visibleCells

或者您可以通过记住它的 indexPath 来取消选择上一个单元格。并选择一个新的并记住它的 indexPath。这是最有效的变体。

或者您可以在想更改选择时致电[self.tableView reloadData]。这将不太有效,但更短且更易于实施。

更新:

只是使用不同的单元格选择条件,而不是基于值,而是基于 indexPath。并提醒我为什么需要手动选择单元格?我的意思是手动设置backgroundColor 和textColor 可以通过[UITableViewCell setSelected:] 选择自动。

【讨论】:

  • 你能举个例子吗?我不太遵循前两种方法。
  • 我手动设置单元格,因为我有 3 个这样的文本框。选择时,它们中的每一个都会为 tableview 填充不同的值。点击行时,所有值都会更改为被点击的行。我尝试了您展示的setSelected 方法,但没有成功。
  • indexPath 是向前迈出的一步,但是我忘了提及其他要求。以上更新
【解决方案2】:

感谢@k06a,我的解决方案

NSIndexPath *selectedIndexPathA;
NSIndexPath *selectedIndexPathB;

在didSelectRowAtIndexPath 中,我将 indexPath 传递给将设置这些值的方法:

[self setOtherFieldsWithIndexPath:indexPath];

在setOtherFieldsWithIndexPath方法中

if (rowA) { selectedIndexPathA = indexPath; }
else if (rowB) { selectedIndexPathB = indexPath; }
else {...}

最后在cellForRowAtIndexPath

if (selectedIndexPathA.row == indexPath.row) {
    cell.backgroundColor = [UIColor colorWithRed:220.0/255.0 green:220.0/255.0 blue:220.0/255.0 alpha:1.0];
    cell.textLabel.textColor = [UIColor whiteColor];
}
else if (selectedIndexPathB.row == indexPath.row) {
    cell.backgroundColor = [UIColor colorWithRed:220.0/255.0 green:220.0/255.0 blue:220.0/255.0 alpha:1.0];
    cell.textLabel.textColor = [UIColor whiteColor];
}
else {
    cell.backgroundColor = [UIColor clearColor];
    cell.textLabel.textColor = [UIColor blackColor];
}

不确定这是否是最佳解决方案,但它目前按我希望的方式工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-21
    • 2012-11-03
    • 1970-01-01
    • 2016-01-18
    • 1970-01-01
    • 2017-07-06
    • 2011-10-29
    相关资源
    最近更新 更多