UITableView的一些常用方法

本文详细介绍了如何使用Swift创建并配置一个自定义的UITableView,包括设置代理、注册重用池、设置每行高度、行数、显示内容、分区、分区标题、头高度、分区头视图、脚部高度、右侧索引数组、点击事件等功能。

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

- (void)viewDidLoad {

    [super viewDidLoad];

    

    UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped]; 

//    设置代理

    tableView.delegate = self;

    tableView.dataSource = self;

//    注册重用池

    [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCellIdentifier"];

    [self.view addSubview:tableView];

    [tableView release];

    

}


//返回每行高度 -- (默认44)

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

    return 100;

}

//返回行数

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

    return 8;  

}


//每个row显示的内容(cell

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

    UITableViewCell *cell = [tableView      dequeueReusableCellWithIdentifier:@"UITableViewCellIdentifier"];

    

//    设置文字

    cell.textLabel.text = @"";

    cell.detailTextLabel.text = @"";

    cell.imageView.image = [UIImage imageNamed:@"Image"];

    

    return cell;

}



//分区

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

    return 4;

}

//分区标题

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {

   return @"A";


}

//分区头高度

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return 30;

}



- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    UIView *vv = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 10)];

    vv.backgroundColor = [UIColor greenColor];

    return vv;

}

//    如果不想显示每个sectionfooter,则高度返回0

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {

//    当直接返回0的时候,系统会认为他是无效值,不会做任何更改,所以返回float类型的最小值

    return CGFLOAT_MIN;

}


//返回右侧的索引数组

//section相互呼应

-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {

    return @[@"A", @"B", @"C", @"D"];

}

//点击事件

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

//   取消选中状态

    [tableView deselectRowAtIndexPath:indexPath animated:YES];


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值