美文网首页
纯代码创建tableView

纯代码创建tableView

作者: 贼海鸥 | 来源:发表于2017-04-12 09:46 被阅读0次

1.创建全局的tableView

@interface ViewController ()
@property (nonatomic , strong) UITableView *tableview;
@end

2.懒加载tableView

- (UITableView *)tableview {
    if (_tableview == nil) {
        _tableview = [[UITableView alloc] initWithFrame:self.view.frame];
        _tableview.delegate = self;
        _tableview.dataSource = self;
    }
    return _tableview;
}

3.在view上添加tableView

[self.view addSubview:self.tableview];
// 去掉多余的cell
self.tableview.tableFooterView = [UIView new];

4.自定义cell的样式
首先,在cell的.h文件中,写一个方法(这个方法可以基本通用)

+ (instancetype)cellWithTableView:(UITableView *)tableView;

然后,实现这个方法

+ (instancetype)cellWithTableView:(UITableView *)tableView {
    static NSString *ID = @"cellID";
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    return cell;
}

这个时候,初始化cell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        [self initWithView];
    }
    return self;
}
// 在这个方法里面添加各种控件,但是不要在这个方法里面设置控件的尺寸大小
- (void)initWithView {
    
}
// 在这个方法里面设置尺寸大小
- (void)layoutSubviews {
    [super layoutSubviews];

}

5.自定义完cell之后,实现tableView的代理方法

#pragma mark - UITableViewDataSource , UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 5;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TableViewCell *cell = [TableViewCell cellWithTableView:tableView];
    cell.textLabel.text = [NSString stringWithFormat:@"%ld" , (long)indexPath.row];
    return cell;
}

效果图:如下

77DC88C7-E332-4208-BFBC-45CD01210D00.png

这样做的好处是控制器里面的代码可以尽量的精简.当然了,还可以精简的,那就是将tableView也封装起来,到时候,只需要在view中加一个封装的view就好了.

相关文章

网友评论

      本文标题:纯代码创建tableView

      本文链接:https://www.haomeiwen.com/subject/eywpattx.html