用SnapKit适配tableviewcell的自适应高度

iOS的时候经常用masnory进行适配,SnapKit是一个用Swift封装的autolayout自动适配的库,用法其实和masnory类似。

创建工程,用cocopods导入SnaoKit库

Podfile文件

platform :ios, '8.0'

use_frameworks!pod 'SnapKit'

在applicationdidFinishLaunchingWithOptions中加入如下代码

window =  UIWindow(frame: UIScreen.mainScreen().bounds)

window?.backgroundColor = UIColor.whiteColor()

window?.makeKeyAndVisible()

let vc:XLRootViewController = XLRootViewController()

let NVC:UINavigationController = UINavigationController(rootViewController: vc);

window?.rootViewController = NVC

viewdidload中代码

override func viewDidLoad() {

super.viewDidLoad()

self.CreateUI()

// Do any additional setup after loading the view.

}

func CreateUI() -> Void {

self.title = "自动布局"

let ChatTable:UITableView = UITableView(frame: CGRect(x: 0, y: 0, width: CGRectGetWidth(self.view.frame), height: CGRectGetHeight(self.view.frame)), style: UITableViewStyle.Plain)

self.view.addSubview(ChatTable)

ChatTable.delegate = self

ChatTable.dataSource = self

ChatTable.separatorStyle = UITableViewCellSeparatorStyle.None

ChatTable.registerClass(XLLeftCell().classForCoder, forCellReuseIdentifier:LeftCellIDF)

ChatTable.registerClass(XLRightCell().classForCoder, forCellReuseIdentifier: RightCellIDF)

// 设置大概高度

ChatTable.estimatedRowHeight = 80

// 设置行高为自动适配

ChatTable.rowHeight = UITableViewAutomaticDimension

}

自定义cell

现将子视图加入俯视图,在用SnapKit进行适配

self.contentView.addSubview(HeadImg!)

HeadImg?.snp_makeConstraints(closure: { (make) in

make.right.equalTo(self.contentView).offset(-15)

make.top.equalTo(self.contentView).offset(15)

make.width.equalTo(40)

make.height.equalTo(40)

})

let BacImgv:UIImageView = UIImageView.init()

BacImgv.image = IMG

self.contentView.addSubview(BacImgv)

BacImgv.snp_makeConstraints { (make) in

make.right.equalTo((HeadImg?.snp_left)!).offset(-20)

make.top.equalTo(self.contentView).offset(15)

make.bottom.equalTo(self.contentView).offset(-15)

make.width.lessThanOrEqualTo(200)

make.height.lessThanOrEqualTo(1000)

}

上面的代码中用lessThanOrEqualTo来对Label的父视图进行适配

在需要根据label上字数自适应高度的Label上这样适配

ContainLab.numberOfLines = 0

ContainLab.backgroundColor = UIColor.clearColor()

self.contentView.addSubview(ContainLab)

ContainLab.snp_makeConstraints(closure: { (make) in

make.edges.equalTo(BacImgv).inset(UIEdgeInsets.init(top: 20, left: 20, bottom: 20, right: 20))

})

效果图是这样

代码下载

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 写在前面(Github地址)主要记录了,我在学习Snapkit中的一些整理记录学习目标好好学习如何用代码来做自动布...
    Manba_小洛阅读 5,687评论 0 0
  • iOS_autoLayout_Masonry 概述 Masonry是一个轻量级的布局框架与更好的包装AutoLay...
    指尖的跳动阅读 4,987评论 1 4
  • (一)Masonry介绍 Masonry是一个轻量级的布局框架 拥有自己的描述语法 采用更优雅的链式语法封装自动布...
    木易林1阅读 7,176评论 0 3
  • Masonry是一个轻量级的布局框架,拥有自己的描述语法,采用更优雅的链式语法封装自动布局,简洁明了并具有高可读性...
    3dcc6cf93bb5阅读 5,835评论 0 1
  • 看书&旅行,灵魂要有一个在路上 云南是我一直想去的一个地方,恰逢最近烦心事比较多,决定自己一个人去一趟向往已久的旅...
    哈密瓜伴西瓜阅读 3,532评论 0 0

友情链接更多精彩内容