如何选择尚未显示的UITableView行?

时间:2012-01-27 21:20:47

标签: iphone ios objective-c xcode

我不确定我是否正确地表达了我的问题,所以这里是细节。 我正在使用UITableView来显示可用字体列表。当列表是dsiplayed时, 一次只显示大约12行,所以如果之前选择的字体尚未显示,我在第一次显示视图时无法选择它。

我想要的是在视图出现时选择单元并显示在列表的中心。但是由于UITableView只根据需要加载数据,这是我能得到的最好的结果:

EDITED 我已经尝试了这个但它不起作用(滚动时只是简单选择了单元格):

    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *CellIdentifier = @"Cell";
        UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if(cell==nil){
            cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }
        [cell.textLabel setText:[fontArray objectAtIndex:indexPath.row]];
        [cell.textLabel setFont:[UIFont fontWithName:[fontArray objectAtIndex:indexPath.row] size:16]];
        [cell setSelectionStyle:UITableViewCellSelectionStyleBlue];
//select the cell/row if it matches the  current font
        if([cell.textLabel.text isEqualToString:currentFontName]){
            cell.selected=YES;
        }
        NSLog(@"returning cell %@",cell.textLabel);
        return cell;
    }

3 个答案:

答案 0 :(得分:1)

1 - 使用- (BOOL)isEqualToString:(NSString *)aString

进行比较

1a - 替换你的测试

if([cell.textLabel.text isEqualToString:currentFontName]){
    cell.selected=YES;
}

通过

cell.selected = [cell.textLabel.text isEqualToString:currentFontName];

1b - 如果您需要显示所选字体,可以在加载TableView之前执行此操作:

NSIndexPath * selFntPath = [NSIndexPath indexPathForRow: [fontArray indexOfObject: currentFontName] 
                                              inSection: 0];

[tableView scrollToRowAtIndexPath: selFntPath 
                 atScrollPosition: UITableViewScrollPositionMiddle
                         animated: NO];

2 - 检查您是否未取消选择

中的单元格

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath委托方法。

这是大多数示例代码中的经典行为。

选项:您可以保留select属性以供用户选择并切换特定控件(即使用单元格的accessoryType属性进行复选标记)以显示系统选定的行。

答案 1 :(得分:0)

这可能是正确的方法,但您无法通过指针比较来测试NSString s的相等性。您需要- (BOOL)isEqualToString:(NSString *)aString而不是==

答案 2 :(得分:0)

我在另一个线程中找到了解决方案 - 问题与重用单元格有关。如果我不重复使用单元格,那么一切正常。当仅选择一个项目时,重复使用单元格也会导致出现多个复选标记的问题。感谢那些贡献的人。

编辑:如果我不回答我自己的问题,请告诉我......还告诉我解决问题的正确方法!

编辑2:这个帖子也有帮助 UITableViewCell going black when selected programmatically