转载

iOS开发 | swift中自动布局框架SnapKit的使用

OC有masonry,swift有SnapKit。

熟悉masonry的同学上手SnapKit非常快,因为语法很像。

这里记录一下常用的几个方法:

先创建一个红色view:

let redView = UIView() self.view.addSubview(redView)          redView.backgroundColor = UIColor.red

创建约束

// 创建约束 redView.snp.makeConstraints { (make) in     // 距离上左下右各20     make.top.left.equalToSuperview().offset(20)     make.bottom.right.equalToSuperview().offset(-20) }

更新约束

// 更新约束 redView.snp.updateConstraints { (make) in     // 距离底部100     make.bottom.equalTo(-100) }

重新设置约束

// 重新设置约束 redView.snp.remakeConstraints { (make) in     // 距离四边100     make.edges.equalTo(UIEdgeInsetsMake(100, 100, 100, 100)) }

label宽度自适应(不设置宽度即可)

// label宽度自适应(不设置宽度) let label = UILabel() self.view.addSubview(label) label.text = "这是一个绿色label" label.backgroundColor = UIColor.green label.font = UIFont.systemFont(ofSize: 15) label.snp.makeConstraints { (make) in     make.left.equalToSuperview()     make.height.equalTo(20)     make.bottom.equalTo(-60) }

并排的两个label,优先让其中一个宽度自适应(别扯我)

// 并排的两个label,优先让右边的label宽度自适应 // 左边的label let leftLabel = UILabel() self.view.addSubview(leftLabel) leftLabel.backgroundColor = UIColor.lightGray leftLabel.text = "这是左边的label" leftLabel.font = UIFont.systemFont(ofSize: 12) // 右边的label let rightLabel = UILabel() self.view.addSubview(rightLabel) rightLabel.backgroundColor = UIColor.orange rightLabel.text = "这是右边的label,优先宽度自适应内容" rightLabel.font = UIFont.systemFont(ofSize: 12) // 别扯我,谢谢(这就是右边label优先宽度自适应的关键代码) rightLabel.setContentHuggingPriority(1000, for: UILayoutConstraintAxis.horizontal); leftLabel.snp.makeConstraints { (make) in     make.left.equalToSuperview()     make.bottom.equalTo(-20)     make.height.equalTo(20) } rightLabel.snp.makeConstraints { (make) in     make.left.equalTo(leftLabel.snp.right)     make.bottom.height.equalTo(leftLabel)     make.right.equalToSuperview() }

效果:

iOS开发 | swift中自动布局框架SnapKit的使用

  • 作者:无夜之星辰

  • 链接:http://www.jianshu.com/p/8ce0a616a86e

  • 來源:简书

  • 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

正文到此结束
Loading...