如何实现自定义单元格
我正在尝试改变tableview从generics到自定义的单元格,并创build了一个新的tableview单元格类。 但是,我无法让单元格识别新的自定义单元格。 相反,它仍然显示通用单元格,虽然我已经在识别检查器中将故事板中的设置更改为自定义,并且还将tableview单元格的类更改为新的自定义单元格。 我还将故事板中单元格中的元素连接到新的自定义类。
我的理解是tableview VC知道从tableView cellForRowAtIndexPath
方法使用哪个类,我也改变了下面的代码。 该项目编译,但继续显示旧的通用单元格。 任何人都可以看到错误或build议还有什么要做?
#import "customCell.h" - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { customCell *cell = (customCell *)[self.tableView dequeueReusableCellWithIdentifier:@"Cell"]; Items *item = [self.fetchedResultsController objectAtIndexPath:indexPath]; return cell; }
在此先感谢您的任何build议。
编辑:
自定义单元格通过拖动元素在桌面视图顶部的故事板中创build。 也许这是问题:
单元格样式设置为自定义:
您需要创build新的UITableViewCell并启用“创buildXIB文件…”。 在XIB中创build自定义单元格,并将其作为您刚刚创build的类的自定义类。
然后在tableView cellForRowAtIndexPath
注册Nib :(它很快,但我敢打赌,你可以找出目标C并行…)
tableView.registerNib(UINib(nibName: "YourUITableViewCellClass", bundle: nil), forCellReuseIdentifier: "YourCustomIdentifierFromTheCustomClass")
然后访问你的单元格:
var cell = tableView.dequeueReusableCellWithIdentifier("YourCustomIdentifierFromTheCustomClass")
就是这样。
selectStoryboard上的单元格,然后在该字段中input您的class级的名称。
当你从标识符中出列它时,它将是该类的一个实例。
当您创build自定义单元格时,您必须执行以下操作:
-
在故事板单元上设置标签,图像等。
-
创build一个自定义单元类(从UITableViewCellinheritance)(CustomCell.h&.m),CustomCell.h具有标签,图像等iboutlet的所有属性,并在实现中综合它们。
-
创build这个自定义类后,回到故事板,select自定义单元格,将其类改为CustomCell,并给它一些标识符,如“MyCustomCell”,然后右键单击自定义单元格,并将IBOutlets与标签连接。
-
现在,在您正在实现UITableView的类中导入CustomCell类,并使用您在CustomCell类中定义的属性。
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *MyIdentifier = @"MyCustomCell"; CustomCell*cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] autorelease]; } // Here we use the provided setImageWithURL: method to load the web image // Ensure you use a placeholder image otherwise cells will be initialized with no image [cell.imageView setImageWithURL:[NSURL URLWithString:@"http://example.com/image.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder"]]; cell.myCustomLabel.text = @"My Text"; return cell; }
您可以通过拖动单元格视图在主要故事板中创build自定义单元格。
为该原型创build自定义类。
在标识符检查器中提到类名。
将该类导入到您的视图控制器.h文件。
并将您的自定义从主要故事板连接到自定义的class.h文件。
有用!。