如何正确地继承UITableViewController

时间:2013-01-31 19:12:34

标签: ios objective-c cocoa-touch

我有一个UITableViewController,其中我在cellForRowAtIndexPath方法中定义了一些特定的单元格属性。我实际定义任何特定内容的唯一方法是cellForRowAtIndexPath方法。我没有包括任何其他方法。 (基本上UITableViewController除了cellForRowAtIndexPath之外是空的)

现在,我正在尝试基于这个UITableViewController进行子类化,但我的问题是如何为sublcass设置cellForRowAtIndexPath?如果我将其留空,应用程序会崩溃,因为它需要定义一个单元格。但是,它不应该使用基类中定义的单元格吗?

我究竟需要在子类'cellForRowAtIndexPath方法中使用我在基类中创建的单元格设置?

编辑我被告知解决方案,对于任何想知道的人,你用类似

之类的内容调用你的子类中的超级类
UITableViewCell *cell = (UITableViewCell *)[super tableView:tableView cellForRowAtIndexPath:indexPath];
return cell;

这会将super的单元格返回到您的sublcass,然后返回该单元格。

4 个答案:

答案 0 :(得分:1)

此方法是表视图数据源协议的必需部分,您需要指定该协议。如果你看一下UITableViewController的开发者文档,你会看到cellForRowAtIndexPAth不是它的函数;它位于UITableViewDataSource which you can find here下。这意味着,基类中没有实现;协议中的函数是抽象的,你应该扩展它们并实现它们。

如果您打算创建一个空表,则可以返回空单元格。只需分配它们并在函数中返回它们;子类化表视图单元格不是必需的。一旦您的应用程序停止崩溃,您可以指定所需的文本。使用indexPath使不同部分或不同行的单元格指定不同的文本。

答案 1 :(得分:1)

如果我理解正确,您需要在UITableViewCell的实施中使用自定义tableview:cellFowRowAtIndexPath:

您需要使用自定义类和registerClass:forCellReuseIdentifier:中定义的重用标识符调用tableview:cellFowRowAtIndexPath:,以使其返回此类的实例。

例如:

- (void)viewDidLoad
{
   [super viewDidLoad];
   [self.tableView registerClass:[CustomTableViewCell class] forCellReuseIdentifier:@"CustomCell"];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"CustomCell";
    CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    // Configure the cell...

    return cell;
}

别忘了拨打#import "CustomTableViewCell.h"

答案 2 :(得分:0)

你的继承和授权令人困惑。请注意,UITableView需要一个类UITableViewDelegateUITableViewDataSource。此类不需要从UITableView继承。我认为通过继承UITableViewCell

,您可以更好地了解自己要做的事情

答案 3 :(得分:0)

我想你会发现你的UITableViewController - 包含cellForRowAtIndexPath实际上已经是UITableViewController的子类。它的标题将如下所示:

#import <UIKit/UIKit.h>

@interface MyTableViewController : UITableViewController

@end

UITableViewController的区别是

  • 它有一个self.tableView属性,它保存对tableView的引用。
  • 它为通常的UIViewController超类添加了另外两个属性和一个方法,但更重要的是......
  • 它(通常)充当tableView
  • 的委托和数据源

后者意味着它必须实现至少两个数据源方法。作为委托方法,这些是在UITableViewController超类中实现而不是,因此必须包括两者:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    // Configure the cell...

    return cell;
}

您已实现cellForRowAtIndexPath,但您还需要实现numberOfRowsInSection:以便表知道它需要多大。

相关问题