- Constraint 修改约束
// ViewController.swift
import UIKit
var TopScaleImg_H: CGFloat = 300
class ViewController: UIViewController {
var topConstraint:Constraint?
lazy var topScaleImgView: UIImageView = {
let img = UIImageView(image: UIImage(named: "home_block_green_a"))
img.contentMode = .ScaleAspectFill
img.backgroundColor = UIColor.orangeColor()
return img
}()
lazy var tableView: UITableView = {
let t = UITableView(frame: CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height), style: .Plain)
t.contentInset = UIEdgeInsets(top: TopScaleImg_H, left: 0, bottom: 0, right: 0)
t.delegate = self
t.dataSource = self
t.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cellID")
return t
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.tableView.backgroundColor = UIColor.clearColor()
self.view.addSubview(self.tableView)
self.view.insertSubview(self.topScaleImgView, belowSubview: tableView)
self.topScaleImgView.snp_makeConstraints { (make) in
make.left.equalTo(self.view.snp_left)
make.right.equalTo(self.view.snp_right)
make.top.equalTo(self.view.snp_top)
self.topConstraint = make.height.equalTo(TopScaleImg_H).constraint
}
}
func scrollViewDidScroll(scrollView: UIScrollView) {
let offsetY = scrollView.contentOffset.y
if offsetY < 0{
self.topConstraint?.updateOffset(-offsetY)
}else{
self.topConstraint?.updateOffset(offsetY)
}
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource{
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 30
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Default, reuseIdentifier: "cellID")
cell.textLabel?.text = "row \(indexPath.row)"
cell.backgroundColor = UIColor.grayColor()
return cell
}
}
常用总结:
-
重做约束:
snp_remakeConstraints (先会先清除掉之前所有被SnapKit设置的约束。)
+ 删除约束:
- 要实现对现有的约束进行更新或者移除,我们需要先将约束的结果赋值给一个局部变量或一个类属性,然后对这个约束的引用进行操作。
- 保存 相关约束
view.snp_makeConstraints { (make) -> Void in
make.width.height.equalTo(150)
make.centerX.equalTo(self.view)
self.topConstraint = make.top.equalTo(self.view).offset(40).constraint
} - 移除约束
self.topConstraint?.uninstall()
+ 更新修改相关约束
- 保存 约束 引用
var topConstraint:Constraint?
topView.snp_makeConstraints { (make) -> Void in
make.width.height.equalTo(100)
make.centerX.equalTo(self.view)
self.topConstraint = make.top.equalTo(self.view).offset(10).constraint
} - 更新修改约束
self.topConstraint?.updateOffset(5)
+ 使用snp_updateConstraints更新约束
网友评论