自定义UITableViewCell类问题

时间:2014-04-09 02:27:32

标签: ios objective-c uitableview

我已经在网上阅读了很多关于如何创建自定义单元子类的教程,但我仍然有点困惑。当我尝试按照此问题中的说明进行操作时,我最终得到的错误是tableView不是ViewController对象的有效属性。

我创建了UITableViewCell的新子类,名为CustomBookClass。我已经使用CustomBookClass.h文件连接了这些属性。

#import <UIKit/UIKit.h>

@interface CustomBookCell : UITableViewCell

@property (weak, nonatomic) IBOutlet UIImageView *bookImage;
@property (weak, nonatomic) IBOutlet UILabel *bookTitle;
@property (weak, nonatomic) IBOutlet UILabel *dateAdded;

@end

然后我进入我的ViewController.m文件来编辑viewDidLoad方法。

- (void)viewDidLoad
{
[super viewDidLoad];

[self.tableView.delegate = self];
[self.tableView.dataSource=self];

[self.tableView registerClass:[CustomBookCell class]forCellReuseIdentifier:@"Custom    
Cell"];

}

我在tableView上收到错误,说该属性不存在,即使在ViewController.h文件中,我也包括表格视图。

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITableViewDelegate,   
UITableViewDataSource>

@end

我确定我在这里遗漏了一些非常明显的东西,因为这是我第一次尝试这个。谁能帮我吗?谢谢!

2 个答案:

答案 0 :(得分:0)

UIViewController没有该属性。即使您将Delegate和DataSource协议分配给它。但是你可以做几件事。

  1. 自己将表格视图链接到ViewController。这意味着,创建一个名为tableView的商品/商店。
  2. 继承自UITableViewController而非UIViewController
  3. 两者都应该有用。

    编辑:哦和行:

    [self.tableView.delegate = self];
    [self.tableView.dataSource=self];
    

    没有意义。它们应该是:

    1. self.tableView.delegate = self;self.tableView.dataSource = self;
    2. [self.tableView setDelegate:self];[self.tableView setDataSource:self]
    3. 以1为首选。 (编辑:选项#2实际上是错误的代码,我的错。)

答案 1 :(得分:0)

无需在TableViewCell类

中设置委托和数据源

简单制作一个属性并合成你的表视图项

@property (weak, nonatomic) IBOutlet UIImageView *bookImage;

@property (weak, nonatomic) IBOutlet UILabel *bookTitle;

@property (weak, nonatomic) IBOutlet UILabel *dateAdded;

现在在tableView控制器类中导入您的单元类

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"SimpleTableCell";

    SimpleTableCell *cell = (SimpleTableCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil) 
    {

        //If you are using xib for representing your UI then add a nib file.

        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SimpleTableCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    } 

    cell.bookTitle.text = [tableData objectAtIndex:indexPath.row];
    cell.bookImage.image = [UIImage imageNamed:[thumbnails objectAtIndex:indexPath.row]];
    cell.dateAdded.text = [prepTime objectAtIndex:indexPath.row];

    return cell;
}

有关详细信息,请查看此link

相关问题