首页 > 技术文章 > 如何利用TableView显示自定义nib中创建的UITableViewCell或子类?

fortunely 2015-12-27 22:23 原文

  1. 创建nib文件 cell.xib

  2. 在nib中拖一个UITableView出来,设置其reuse Identifier,再根据cell UI需要拖出view摆放好

  3. 创建ViewController及tableview

  4. 创建TableView在ViewController中的输出口(IBOutlet) tableview

  5. 设置TableView的delegate和datasource(如果运行时发现所有表格单元为空白,很可能是这一步忘记做了)

  6. viewDidLoad中注册nib文件(tableview registerNib:)

  7. 让ViewController遵循TableView的<UITableViewDataSource, UITableViewDelegate>协议

  8. 实现协议方法

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

其中,

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

如果利用dequeueReusableCellWithIdentifier:forIndexPath,则无需判断cell是否为nil,然后再创建,因为此方法会在复用队列中无可用自动调用注册的文件或类创建新对象。如果想响应点击某个单元格,需要实现-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

推荐阅读