美文网首页
用SnapKit适配tableviewcell的自适应高度

用SnapKit适配tableviewcell的自适应高度

作者: Alfred_小乐 | 来源:发表于2016-06-28 16:56 被阅读2519次

    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))

    })

    效果图是这样

    代码下载

    相关文章

      网友评论

          本文标题:用SnapKit适配tableviewcell的自适应高度

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