如何在不使用XIB的情况下创建自定义UITableViewCell

Sat*_*yam 8 iphone uitableview

我找到了很多关于如何使用XIB创建自定义表视图单元的教程,但是是否可以在不使用XIB的情况下创建自定义表视图单元?有人能帮我吗?

Ana*_*tam 5

是的,您可以在不使用XIB的情况下创建自定义表格视图单元格.

为此,您必须使用UITableViewCell的子类在Xcode中创建一个新类.在这里,您无法选择任何XIB选项.

现在打开您的自定义UITableViewCell类,这里的代码将实现您想要的:

#import "CustomCell.h"

@implementation CustomCell

@synthesize ivUser;
@synthesize lblUserName;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:
(NSString *)reuseIdentifier

{

   self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
      if (self) {
           // Initialization code

        ivUser = [[UIImageView alloc] initWithFrame:CGRectMake(4.0f, 3.0f, 39.0f,
        38.0f)];
        lblUserName = [[UILabel alloc] initWithFrame:CGRectMake(58.0f, 8.0f, 50.0f,
        27.0f)];

        [self.contentView addSubview:ivUser];
        [self.contentView addSubview:lblUserName];

     }

   return self;
}
Run Code Online (Sandbox Code Playgroud)

现在根据需要设置子视图坐标,然后在CellForRowAtIndexPath中使用此单元格,它应该可以工作.

  • 在我的tableviewcontroller中,我应该使用的myCellIdentifier:`CustomCell*cell = [tableView dequeueReusableCellWithIdentifier:@"myCellIdentifier"];`? (2认同)
  • 在viewDidLoad中包含以下内容:`[self.tableView registerClass:[CustomCell class] forCellReuseIdentifier:@"myCellIdentifier"];` (2认同)