iOS的時(shí)候經(jīng)常用masnory進(jìn)行適配危融,SnapKit是一個(gè)用Swift封裝的autolayout自動(dòng)適配的庫(kù),用法其實(shí)和masnory類似盆驹。
創(chuàng)建工程冈钦,用cocopods導(dǎo)入SnaoKit庫(kù)
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 = "自動(dòng)布局"
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)
// 設(shè)置大概高度
ChatTable.estimatedRowHeight = 80
// 設(shè)置行高為自動(dòng)適配
ChatTable.rowHeight = UITableViewAutomaticDimension
}
自定義cell
現(xiàn)將子視圖加入俯視圖,在用SnapKit進(jìn)行適配
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來(lái)對(duì)Label的父視圖進(jìn)行適配
在需要根據(jù)label上字?jǐn)?shù)自適應(yīng)高度的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))
})
效果圖是這樣