如何在视图加载时预先选择 UITableViewCell?

Jus*_*ral 2 iphone objective-c uitableview ios

我正在研究在表格视图中选择单元格时播放声音的东西。tableView 由带有声音名称的 NSString 数组填充。

我有一个对象作为控制器的一部分,它有一个声音对象,当您单击单元格时,它会播放声音对象的正确文件名称。

如何在视图首次加载时预先选择一个 TableView 单元格,并让它在 tableView 首次加载时不播放声音。

这是我目前的选择代码。

- (UITableViewCell *)tableView:(UITableView *)tableView
     cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
TMVSoundCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SoundCell" forIndexPath:indexPath];

[self configureCell:cell forRowAtIndexPath:indexPath];

return cell;
}

- (void)configureCell:(TMVSoundCell *)cell
forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.soundTitle.text = [[self.soundArray objectAtIndex:indexPath.row]name];


if (self.selectedRowIndexPath != nil && [indexPath compare:self.selectedRowIndexPath]    == NSOrderedSame)
{
           cell.soundTitle.textColor = [UIColor whiteColor];
           self.itemView.item.sound = [self.soundArray objectAtIndex:indexPath.row];

    [DataManager saveContext];
}

else
{
        cell.soundTitle.textColor = AppDelegate.atmosphere.currentColor;
}


}


#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSMutableArray *indexPaths = [NSMutableArray arrayWithObject:indexPath];

if (self.selectedRowIndexPath)
{

    if ([indexPath compare:self.selectedRowIndexPath] == NSOrderedSame)
    {
        self.selectedRowIndexPath = nil;
    }

    else
    {

        [indexPaths addObject:self.selectedRowIndexPath];
        self.selectedRowIndexPath= indexPath;
    }
}

else
{
    self.selectedRowIndexPath = indexPath;
}

[tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ams 6

用于selectRowAtIndexPath以编程方式选择单元格。

根据文档

调用此方法不会导致委托收到 tableView:willSelectRowAtIndexPath: 或 tableView:didSelectRowAtIndexPath: 消息,也不会向观察者发送 UITableViewSelectionDidChangeNotification 通知。


Ced*_*rie 5

您需要selectRowAtIndexPath调用cellForRowAtIndexPath. Swift4中的示例:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

    if ADD_YOUR_CONDITION_HERE {
        self.tableView.selectRow(at: indexPath, animated: false, scrollPosition: .top)
    }

    return cell
}
Run Code Online (Sandbox Code Playgroud)