现在的位置: 首页 > 综合 > 正文

IB中如何自定义TableViewCell

2018年07月26日 ⁄ 综合 ⁄ 共 1633字 ⁄ 字号 评论关闭

1. 在xCode中选择新建->User Interface -> Empty XIB。(指定一个有意义的名字最好,本例BaseTableCell)

2. 打开新建的这个空XIB文件,将UITableViewCell控件拖放到xib窗口中。

3. 添加样式和其他控件到这个cell控件中。(UITextField & UITextView不适用于表格视图单元)

4. 打开属性检查器,设置重用标识符号Identifier,如:BaseTableCell

 //可选中Title标签,设置它的tag属性值为101,之后可以利用自定义视图中Title标签的tag值进行对cell的子视图的操作:

复制代码
#define TEXTLABEL ((UILabel *)[cell viewWithTag:101])

- (UITableViewCell *)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//设置重用
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BaseTableCell"];
if(!cell) {
//增加新行
cell = [[[NSBundle mainBundle] loadNibNamed:@"BaseTableCell" owner:self options:nil] lastObject];
}

//设置cell背景
[cell setSelectedBackgroundView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cell_bg.png"]]];
[TEXTLABEL setText:[[UIFont familyNames] objectAtIndex:indexPath.row]];
return cell;
}
复制代码
复制代码
// 可以在以上代理中设置单元格的高度 tableView.rowHeight = 100;
// 也可以在专门设置高度的代理方法中设置表单元格的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 100.0f;
}

// 自定义单元格背景颜色
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
[cell setBackgroundColor:[UIColor redColor]]; //设置背景颜色
[cell setSelectedBackgroundView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cell_bg.png"]]]; //设置选中后的背景
}
复制代码

转载整理自:http://xiaohui3837843.blog.163.com/blog/static/54388740201151635857655/

关于以下语句的解释:
          NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"xib的名字" owner:self options:nil];
          类名 *View = [nib objectAtIndex:0];
注意:在使用此View对象时,如果没有哪个操作具有retain的功能,最好显式地把View retain一次,如果有addObject、addSubview之类的操作则不需要。谨记,这个View不是用alloc、copy等方式创建的,是个自动释放的对象,要特意保留一下它,才不会在用到时出错。

抱歉!评论已关闭.