iphone - 如何在 UITableview 中加载后选择并选中行

标签 iphone objective-c ios xcode uitableview

我有一个选择,将仅选择 1 行类别。 但我希望它在加载时选择烈酒行。

像这样:

enter image description here

目前,没有选择任何内容:

enter image description here

我应该在哪里进行比较才能使其selectRowAtIndexPath

//自定义表格 View 单元格的外观。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }


    categoryString = [arrayCategory objectAtIndex:indexPath.row];
    cell.textLabel.text = categoryString;
    if (cell.textLabel.text == categoryString) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    else {
        cell.accessoryType = UITableViewCellAccessoryNone;

    }

    return cell;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell* newCell = [tableView cellForRowAtIndexPath:indexPath];
    int newRow = [indexPath row];
    int oldRow = (lastIndexPath != nil) ? [lastIndexPath row] : -1;

    if(newRow != oldRow)
    {
        newCell.accessoryType = UITableViewCellAccessoryCheckmark;
        newCell.highlighted =YES;
        UITableViewCell* oldCell = [tableView cellForRowAtIndexPath:lastIndexPath];
        oldCell.accessoryType = UITableViewCellAccessoryNone;
        lastIndexPath = indexPath;
        oldCell.highlighted = NO;

    }
    [tableView deselectRowAtIndexPath:(NSIndexPath *)indexPath animated:YES];
}

最佳答案

使用 selectRowAtIndexPath:animated:scrollPosition: 方法以编程方式选择行。

代码中需要纠正的地方很少。您应该使用 isEqualToString: 方法来匹配字符串,例如 if ([cell.textLabel.text isEqualToString:categoryString]) {。接下来的事情是,您将 categoryString 分配给 cell.textLabel.text,并在下一行匹配它们,因此它总是返回 YES。我认为您匹配了错误的值。

关于iphone - 如何在 UITableview 中加载后选择并选中行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6953538/

相关文章:

c# - 如何制作像 Popcorn Time 这样的 GUI?

python - 如果我在 Ubuntu 上开始学习 C,它会在我今年夏天晚些时候开始学习 Objective-C 时给我带来优势吗?

ios - 我可以得到 JSON 响应而不是 xml 吗?在 ASIs3bucketRequest 中

ios - 找不到“ConnectyCube/ConnectyCube.h”文件

iphone - 设备上未收到推送通知

iphone - cocos2d : Show entire layer then zoom in on character

iphone - Xcode上的怪异编译错误

iphone - 如何删除工具栏上 UIBarButtonItems 之间的默认可用空间?

objective-c - ARC 不允许将 'int' 隐式转换为 'id _Nonnull'

ios - 自定义标注气泡 iOS