ios - 多个动态原型(prototype)单元的索引路径

标签 ios uitableview uiviewcontroller uistoryboard nsindexpath

男士们,

我需要一些帮助。这几乎就像我知道我在尝试做什么,但是在编写代码时我一直无法让它工作。场景是我有一个 View Controller ,里面有一个 TableView 。我的表格 View 有三种不同的动态原型(prototype),因为我有三种不同的单元格。现在,我要做的就是指定在哪一行中生成哪个原型(prototype)单元格。我还在 Storyboard 中为每个原​​型单元格提供了唯一标识符。

我理解事物的方式是我的 cellforRowatIndexpath 方法需要了解在该行中显示哪种单元格,然后选择标识符,出列并根据需要设置内容。

相应地,这是我正在尝试做的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath   * )indexPath
{
    if(indexPath.row==0)
    {
        static NSString *CellIdentifier = @"HelloCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault      reuseIdentifier:CellIdentifier];
        }

        // configure your cell here...

        return cell;
    }
}

不幸的是,事情没有按计划进行,我的应用程序崩溃了
2013-02-07 16:47:39.859 ProjectsABC30068:c07] * 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[NSIndexPath setTableViewStyle:]:无法识别的选择器发送到实例 0x83812e0”错误。

由于我已正确设置数据源和委托(delegate),因此 TableView 没有问题。并且还为表格 View 做了一个导出。

我还尝试将 cellforRowAtIndexPath 中的 if 语句更改为 if(myTable.indexPathForSelectedRow==0)。这会在所有单元格中生成动态原型(prototype),但至少应用程序不会停止。

大家觉得是什么问题?

我不知道如何正确使用索引路径,如果有人可以帮助我,我将不胜感激。

最佳答案

使用 Storyboard和动态原型(prototype)单元,您不必担心或检查 dequeueReusableCellWithIdentifier:返回一个零单元格。

你必须做的:

  • 对于每一行,确定正确的单元格标识符并将其提供给 dequeueReusableCellWithIdentifier:
  • 对于每个动态原型(prototype)单元格,确保设置正确的标识符(选择 Storyboard 上的每个单元格,然后在 TableView 单元格部分下的属性检查器中填写标识符)

  • set up cell identifier

    让我们举个例子。假设您有三个原型(prototype)单元格,标识符分别为“Cell1”、“Cell2”和“Cell3”。并假设您有三行,每行显示一个原型(prototype)单元格。
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        return 3;
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        NSString *identifier = [NSString stringWithFormat:@"Cell%d", indexPath.row + 1];
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    
        cell.textLabel.text = identifier; // just show the identifier as title
        return cell;
    }
    

    关于ios - 多个动态原型(prototype)单元的索引路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14764676/

    相关文章:

    iphone - 在 iOS 自动化期间更改国际设置

    ios - 越狱 iOS 以编程方式开始和结束调用

    ios - Swift - 如何获取嵌入在 UITableView 单元格中的选定控件段?

    ios - 如果结果在通知初始化后更新,我该如何使用 Realm 通知?

    ios - xib 通知解除分配错误中的自定义 UIView

    objective-c - NSTimer:释放时是否调用了invalidate?

    ios - 为什么 Storyboard 退出按钮中缺少 IBAction 方法?

    arrays - 如何使用prepareForSegue从二维数组传递值

    ios - UIView 子类中的 UIButton 不起作用,Swift

    iOS 自动布局 : get width of views inside a view in ViewController