一、附上 SnapKit 在 github 的地址:https://github.com/SnapKit/SnapKit
官方指导添加约束:https://github.com/SnapKit/SnapKit#usage
SnapKit 3.0 Migration Guide: https://github.com/SnapKit/SnapKit/blob/master/Documentation/SnapKit%203.0%20Migration%20Guide.md
二、具体使用
Swift 3.0 使用懒加载
//头像 lazy var headerImageView: UIImageView = { let imgView: UIImageView = UIImageView() imgView.backgroundColor = UIColor.red return imgView }() //title lazy var titleLabel: UILabel = { let time: UILabel = UILabel() time.font = UIFont.boldSystemFont(ofSize: 15) time.text = "工作通知:iOS" return time }() //时间 lazy var timeLabel: UILabel = { let time: UILabel = UILabel() time.font = UIFont.systemFont(ofSize: 10) time.textColor = UIColor.lightGray time.text = "昨天" time.textAlignment = .right time.baselineAdjustment = .none return time }() //描述 lazy var descriptionLabel: UILabel = { let time: UILabel = UILabel() time.font = UIFont.systemFont(ofSize: 13) time.textColor = UIColor.lightGray time.text = "[考勤打卡] 还有六分钟就要上班了,..." time.textAlignment = .left time.baselineAdjustment = .none return time }() //未处理时间1 lazy var noHandleLabel: UILabel = { let time: UILabel = UILabel() time.isHidden = true time.backgroundColor = .red time.font = UIFont.systemFont(ofSize: 10) time.textColor = UIColor.white time.text = "1" time.textAlignment = .center time.baselineAdjustment = .none return time }()
使用 Snapkit 给控件添加约束
func addSubViews() -> Void { self.addSubview(self.headerImageView) self.addSubview(self.titleLabel) self.addSubview(self.timeLabel) self.addSubview(self.descriptionLabel) self.addSubview(self.noHandleLabel) //头像 self.headerImageView.snp.makeConstraints { (make) in make.left.equalToSuperview().offset(10) make.top.equalToSuperview().offset(10) make.bottom.equalToSuperview().offset(-10) make.width.equalTo(self.headerImageView.snp.height) } //title self.titleLabel.snp.makeConstraints { (make) in make.top.equalTo(self.headerImageView) make.left.equalTo(self.headerImageView.snp.right).offset(10) } //时间 self.timeLabel.snp.makeConstraints { (make) in //make.top.equalTo(self.titleLabel.snp.top) make.bottom.equalTo(self.titleLabel.snp.bottom) make.right.equalToSuperview().offset(-10) } //描述 self.descriptionLabel.snp.makeConstraints { (make) in make.left.equalTo(self.titleLabel.snp.left).offset(0) make.bottom.equalTo(self.headerImageView.snp.bottom).offset(0) make.right.equalTo(self.noHandleLabel).offset(-20) } //未处理事件 self.noHandleLabel.snp.makeConstraints { (make) in make.right.equalTo(self.timeLabel.snp.right).offset(0) make.bottom.equalTo(self.descriptionLabel.snp.bottom).offset(0) make.top.equalTo(self.descriptionLabel.snp.top).offset(0) make.width.equalTo(self.noHandleLabel.snp.height).offset(0) } }
效果图:
请发表评论