如何实现自定义单元格

问题描述 投票:0回答:4

我试图将tableview中的单元格从泛型更改为自定义并创建一个新的tableview单元类。但是,我无法让单元格识别新的自定义单元格。相反,它仍然显示通用单元格,虽然我已将故事板中的设置更改为标识检查器中的自定义,并且还将tableview单元格的类更改为新的自定义单元格。我还将故事板中单元格中的元素连接到新的自定义类。

我的理解是tableview VC知道从tableView cellForRowAtIndexPath方法使用哪个类,我也改变了下面的代码。该项目编译但继续显示旧的通用单元格。任何人都可以看到错误或建议还有什么可做的吗?

#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;
}

在此先感谢您的任何建议。

编辑:

通过拖动uielements在tableview顶部的故事板中创建自定义单元格。也许这是个问题:

enter image description here

单元格样式设置为自定义:

enter image description here

ios objective-c uitableview custom-cell
4个回答
2
投票

您需要创建新的UITableViewCell并启用“创建XIB文件...”。在XIB中创建自定义单元格,并将其自定义类作为您刚刚创建的类。

然后在tableView cellForRowAtIndexPath注册Nib :(它很快但我打赌你可以找出目标c并行......)

tableView.registerNib(UINib(nibName: "YourUITableViewCellClass", bundle: nil), forCellReuseIdentifier: "YourCustomIdentifierFromTheCustomClass")

然后访问您的单元格:

var cell = tableView.dequeueReusableCellWithIdentifier("YourCustomIdentifierFromTheCustomClass")

就是这样。


0
投票

在故事板上选择单元格,然后在此字段中输入您的类的名称。

当您从标识符中将其出列时,它将是该类的实例。

enter image description here


0
投票

您可以通过拖动单元格视图在主故事板中创建自定义单元格。

为该原型创建自定义类。

提到标识符检查器中的类名。

将该类导入视图控制器.h文件。

并将您的自定义从主故事板连接到自定义class.h文件。

有用!。


0
投票

创建自定义单元格时,您必须执行以下操作:

  1. 在故事板单元格上设置标签,图像等。
  2. 创建一个自定义单元类(继承自UITableViewCell)(CustomCell.h和.m),CustomCell.h具有标签,图像等iboutlet的所有属性,并在实现中合成它们。
  3. 创建此自定义类后,返回故事板,选择自定义单元格,将其类更改为CustomCell并为其指定一些标识符,如“MyCustomCell”,然后右键单击自定义单元格并将IBOutlets与标签等连接。
  4. 现在,在要实现UITableView的类中导入Custom Cell类,并使用您在Custom Cell类中定义的属性。
- (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; }
© www.soinside.com 2019 - 2024. All rights reserved.