iOS UITableView的基本使用

本文介绍了UITableView如何通过数据源展示数据,包括获取数据行数、设置单元格内容及样式等过程。详细解释了设置单元格背景颜色和辅助视图的方法,并提供了实例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【UITableView控件简单介绍】
一、数据展示
UITableView需要一个数据源(dataSource)来显示数据;
UITableView会向数据源查询一共有多少行数据以及每行显示什么数据;
没有设置数据源的UITableView只是空壳;
凡是遵守UITableViewDataSource协议的OC对象,都可以是UITableView的数据源

二、展示数据的过程
1.调用数据源的方法得到一共有多少组数据
	-(NSInteger)numberOfSectionInTableView:(UITableView *)tableView;
2.调用数据源方法得到每一组有多少行数据
	-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
3.调用数据源方法得知每行显示什么内容
	-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;

cell的一些属性:

(1)设置cell的辅助视图,设置cell.accessoryView(系统提供了枚举型,也可以自定义@父类指针指向子类对象);

(2)设置cell的背景颜色,有两种方式可以设置cell的背景颜色:

通过backgroundColor 和 backgroundView都可以设置cell的背景。但是backgroundView 的优先级比 backgroundColor的高,所以如果同时设置了backgroundColor和backgroundView, 那么backgroundView会盖住backgroundColor

示例:cell.backgroundColor = [UIColorblueColor];

(3)设置cell默认状态的背景

示例1:

   UIView *view = [[UIView alloc] init];

   view.backgroundColor = [UIColor blueColor];

  cell.backgroundView = view;

示例2:

UIImageView *iv = [[UIImageViewalloc] initWithImage:[UIImageimageNamed:@"buttondelete"]];

cell.backgroundView = iv;(父类指针指向子类对象,可以使用图片用简单的操作设置绚丽的效果)

(4)设置cell选中状态的背景

示例:

  UIView *view2 = [[UIView alloc] init];

view2.backgroundColor = [UIColorpurpleColor];

cell.selectedBackgroundView = view2;

tableview的一些属性:

- (void)viewDidLoad
{
    [super viewDidLoad];

    // 1.创建tableview
    UITableView *tableview = [[UITableView alloc] init];
    tableview.frame = self.view.bounds;

    // 2.设置数据源
    tableview.dataSource =self;

    // 3.添加tableview到view
    [self.view addSubview:tableview];
    
    // 4.设置分割线样式
    // tableview.separatorStyle = UITableViewCellSeparatorStyleNone;

    // 5.设置分割线颜色
     接收的参数是颜色的比例值
    tableview.separatorColor = [UIColor colorWithRed:0/255.0 green:255/255.0 blue:0/255.0 alpha:255/255.0];
    
    // 设置tableview的头部视图
    tableview.tableHeaderView = [UIButton buttonWithType:UIButtonTypeContactAdd];
    tableview.tableFooterView = [[UISwitch alloc] init];
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值