UITableView创建

来源:互联网 发布:php 活动报名 源代码 编辑:程序博客网 时间:2024/06/06 07:28

创建tableview需要签协议UITableViewDataSource,UITableViewDelegate

定义属性 @property (nonatomic,strong)UITableView *tableview;


//创建tableviewself.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain];    //签代理    _tableview.delegate = self;    _tableview.dataSource = self;    //设置行高    _tableview.rowHeight = 100;    //分割线    _tableview.separatorStyle = UITableViewCellSeparatorStyleSingleLine;    //分割线颜色    _tableview.separatorColor = [UIColor redColor];    //添加到父视图    [self.view addSubview:_tableview];    //注册cell    [_tableview registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];

//头部名称- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{    return @"头部名称";}//脚部名称- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{    return @"脚部名称";}

也可自定义头部脚部区域
//自定义头部区域- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(100, 100, 100, 30)];    header.backgroundColor = [UIColor redColor];    return header;}//自定义脚部区域- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{    UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 30)];    footer.backgroundColor = [UIColor yellowColor];    return footer;}

#pragma mark - tableview 必须实现的两个方法//cell行数- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{    return 10;}//设置cell的内容- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];    //主标题    cell.textLabel.text = @"标题";    //副标题    cell.detailTextLabel.text = @"副标题";    //左侧图片    cell.imageView.image = [UIImage imageNamed:@"qiaoba"];    //右侧箭头    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;        //自定义右侧图片    UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];    img.image = [UIImage imageNamed:@"qiaoba"];    cell.accessoryView = img;        return cell;    }

//cell高度- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{    return 100;    }//头部高度- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{    return 30;}//尾部高度- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{    return 30;}//tableview右侧索引栏- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{    return @[@"A",@"B",@"C"];}//点击方法- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{    //取消点击效果    [_tableview deselectRowAtIndexPath:indexPath animated:YES];}


0 0
原创粉丝点击