美文网首页
[iOS]UITableView简单封装

[iOS]UITableView简单封装

作者: Jake_Zhu | 来源:发表于2019-04-09 10:43 被阅读0次

自己写UITableview的时候总是要写很大一串,就写了一个初始化的封装,简化一下代码。

文件放在这里:https://github.com/JakeZhucl/CLBaseObject-C

下面是pod

pod 'CLBaseObject-C'

Swift版本

init(_ delegate : UITableViewDelegate & UITableViewDataSource ,
         _ cells : Array<String>) {
        super.init(frame: CGRect.zero, style: .plain)
        if #available(iOS 11.0, *) {
            self.contentInsetAdjustmentBehavior = .never
        } else {
            // Fallback on earlier versions
        }
        self.estimatedRowHeight = 0;
        self.estimatedSectionFooterHeight = 0;
        self.estimatedSectionHeaderHeight = 0;
        self.delegate = delegate
        self.dataSource = delegate
        
        let CLTableViewNameSpace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String
        
        for cellName in cells {
            self.register(NSClassFromString(CLTableViewNameSpace+"."+cellName)!, forCellReuseIdentifier: cellName)
        }

        self.tableFooterView = UIView()
        self.separatorStyle = .none
    }

使用方法

//初始化
tableView = CLTableView(self, ["UITableViewCell"])

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell") as! UITableViewCell
        cell.model = model?.indexArray.data[indexPath.row]
        return cell
    }

Object-C版本

- (instancetype)initWithDelegate:(id<UITableViewDelegate,UITableViewDataSource>)delegate
                       cellsName:(NSArray *)cells
{
    self = [super init];
    if (self) {
        if (@available(iOS 11.0, *)) {
            self.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            // Fallback on earlier versions
        }
        self.estimatedRowHeight = 0;
        self.estimatedSectionFooterHeight = 0;
        self.estimatedSectionHeaderHeight = 0;
        self.delegate = delegate;
        self.dataSource = delegate;
        self.backgroundColor = [UIColor whiteColor];
        for (NSString * cellname in cells) {
            [self registerClass:NSClassFromString(cellname) forCellReuseIdentifier:cellname];
        }
        self.tableFooterView = [UIView new];
        self.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return self;
}

使用方法

//初始化
[[CLTableView alloc]initWithDelegate:self cellsName:@[@"UITableViewCell"]];

//cell代理里面
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
    return cell;
}

相关文章

网友评论

      本文标题:[iOS]UITableView简单封装

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