---
title: "tableviewcell添加label、button"
author: "xiaotongeye"
date: "2014-09-13T22:02:57Z"
tags: []
categories: ["编程语言"]
slug: "tableviewcell-label-button"
draft: false
lastmod: "2014-09-13T17:21:02Z"
id: 2116130
url: "https://xiaotongeye.iteye.com/blog/2116130"
---

1.给tableviewcell添加label，首先

```创建和实例化label

CGRect labelRect = CGRectMake(X, Y,length, width);//x、y表示位置
UILabel *label = [[uilabel alloc] initWithFrame:labelRect];

```

然后可以定义label的一些属性
label.backgroundColor = ;        //设置背景色
label.text = @"Hello World";   //设置内容
label.textColor = ;    //文本颜色
label.backgroundColor = ;   //设置label的背景色透明
在这我添加的前三行颜色不一样

```添加label

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"cell";
    UITableViewCell *cell = [tableview dequeuereusablecellwithidentifier:cellidentifier];
    if (cell == nil){
        cell = [[uitableviewcell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
        //创建label
        CGRect labelRect = CGRectMake(120, 10,130, 20);
        UILabel *label = [[uilabel alloc] initWithFrame:labelRect];
            label.text = @"hello world!!!";
            label.textColor = [uicolor redcolor];
        [cell.contentview addsubview:label];
        label.font = [uifont boldsystemfontofsize:16];
}
    return cell;
}

```

若把;改为则label将建立在tableview中，而不是tableviewcell中
2.给tableviewcell添加button

```创建button

UIButton *button = [uibutton buttonwithtype:uibuttontyperoundedrect];

```

常用的button的属性
button.frame = CGRectMake(150,30,50,20);//button的位置
;
button.backgroundColor = ;

```java

        UIButton *button = [uibutton buttonwithtype:uibuttontyperoundedrect];
        button.frame = CGRectMake(150,30,50,20);
        [button settitle:@"点击" forstate:uicontrolstatenormal];
        button.backgroundColor = [uicolor blackcolor];
        cell.accessoryView = button;   

```

3在cell创建image

```OC

UIImage *image = [uiimage imagenamed:@"meitu@2x.png"];       
        UIImageView *imageView = [[uiimageview alloc] initWithImage:image];
        imageView.frame = CGRectMake(50, 10, 45, 45);
        [cell.contentview addsubview:imageview];

```

还有一种办法

```OC

cell.imageView.image = [uiimage imagenamed:@"meitu@2x.png"];

```

用这个办法该图片显示在cell最左侧imageview中