前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Swift Reusable开源库使用

Swift Reusable开源库使用

作者头像
赵哥窟
发布2020-08-20 16:05:49
1.1K0
发布2020-08-20 16:05:49
举报
文章被收录于专栏:日常技术分享日常技术分享
Reusable

Reusable是一个在swift下使用的开源库。利用protocol extension结合泛型提供了一个优雅的方案来dequeueReusableCell。使用 根据类型获取cell让你的cell声明Reusable或NibReusable协议

//如果cell定义在xib中,声明NibReusableclass

代码语言:javascript
复制
 MyCustomCell: UITableViewCell, NibReusable { }

//如果cell是基于纯代码的,声明Reusableclass

代码语言:javascript
复制
MyCustomCell: UITableViewCell, Reusable { }

接着在tableview或者collectionView中register

代码语言:javascript
复制
 tableView.register(UINib.init(nibName: "MyCustomCell", bundle: nil), forCellWithReuseIdentifier: "MyCustomCell")

粗暴的直接获取cell就可以啦:

代码语言:javascript
复制
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell:myCell = tableView.dequeueReusableCell(for: indexPath, cellType: MyCustomCell.self)
        if dataList.count > indexPath.row{
            cell.model = dataList[indexPath.row]
        }
        return cell
 }

是的。你没有看错,这样就能获取到这个类型的reuse cell,不需要传入reuseIdentifiers,不需要UITableViewCell类型强转。根据类型获取xib中的UIView对象 UIView对象声明NibLoadable协议。

对比

代码语言:javascript
复制
 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell") ?? UITableViewCell.init(style: .subtitle, reuseIdentifier: "UITableViewCell")
        cell.textLabel?.font = UIFont.init(name: "", size: 14.0)
        cell.textLabel?.text = self.dataArray[indexPath.row]
        
        return cell
    }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Reusable
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档