【问题标题】:How do I use a UITableView cell and its elements on prototype cell如何在原型单元格上使用 UITableView 单元格及其元素
【发布时间】:2026-02-15 12:50:02
【问题描述】:

我已经使用这个 Master-Detail 应用程序开始了一个新的 iPad 项目。我不是使用 Interface Builder 创建东西的超级粉丝,但对于这个项目,我必须特别使用它。

我需要创建一个自定义单元格以在MasterViewController 上使用。此单元格将包含一个开关和一个标签。使用界面生成器,我已将这些元素拖到所谓的 Prototype Cells 中,其中称为 TableView Prototype Content。

这就是我得到的。

现在我如何在tableView:cellForRowIndexPath: 中使用它?我是否必须有网点才能使用UILabelUISwitch?我该怎么做?

谢谢

【问题讨论】:

    标签: ios ipad uitableview interface-builder


    【解决方案1】:

    是的。您应该创建一个UITableViewCell 子类,并为您需要访问的每个控件添加IBOutlets。然后,您将您的子类设置为身份检查器中每个原型单元格的自定义类。

    您还需要设置重用标识符。然后,您可以像通常在tableView:cellForRowIndexPath: 中所做的那样使单元格出列:

    YourCustomCellClass *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    

    【讨论】:

    • 啊啊啊,谢谢。那就是我缺少的部分。这就是为什么我从不使用 IB.. ?
    【解决方案2】:

    您需要在 Interface Builder 中为单元格提供Reuse Identifier,之后您将能够通过以下方式访问该单元格:

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    

    如果不进行子类化,您可以给单元格内的每个元素一个标签并使用:

    UISwitch *checkSwitch = (UISwitch *)[cell viewWithTag:-1];
    

    【讨论】:

      【解决方案3】:

      首先创建UITableViewCell 子类并将其设置为Storyboard 中的Prototype Cell。 其次,在 Storyboard 中为您的原型单元格提供一个重用标识符。 在新创建的UITableViewCell 子类中创建UILabelUISwitchIBOutlet 将您的自定义单元格类导入您的 viewcontroller.m 文件 在您的 cellForRowAtIndexPath: 方法中,将您的自定义单元格出列

      -(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
      {
      
       static NSString *cellID = @"cell"; // identifier you have entered in storyboards
       CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
      
       if(!cell)
       {
        cell = [[CustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
       }
      
       //access your custom cell properties from now on
       cell.mySwith // or whatever name you gave it in your outlet
      
       return cell;
      
      }
      

      【讨论】:

        最近更新 更多