話說swift已經更新到4.0了,對于一個資深object-c開發(fā)者來說,感覺又是期望也是無奈??偟靡獙W習swift吧,學吧又沒多大時間,語法還怪異(個人觀點哈)。在新的swift項目中,用到了約束,但是在這么多年的oc書寫中,本人一直用的更輕量級的UIView+AutoLayout,使用起來很是方便,個人覺得,比masonry好用哈。但是swift版本中作者并沒有更新,主要考慮snapkit不好用,而且還存在bug,因此果斷放棄,仿照oc版進行swift編寫。
當然了,主要是為了學習和熟悉語法,還有就是用著方便哈。
附上下載鏈接UIView+AutoLayout
使用起來其實更oc是一樣的,但是為了方便區(qū)別和語法的不同,這里稍微解釋一下:
- 相對父視圖居中,設置大小
let firstView = UIView()
firstView.backgroundColor = UIColor.red
self.view.addSubview(firstView)
firstView.ym_autoCenterInSuperview()
firstView.ym_autoSetDimensionsToSize(size: CGSize(width: 100, height: 100))
- 相對其他view的位置和父視圖的距離
let firstViewLabel = UILabel()
firstViewLabel.text = "firstViewLabel"
firstViewLabel.numberOfLines = 0
firstView.addSubview(firstViewLabel)
//左右兩邊距離父控件各為12,且垂直居中
firstViewLabel.ym_autoPinEdgeToSuperviewEdge(edge: .ALEdgeLeft, inset: 12)
firstViewLabel.ym_autoPinEdgeToSuperviewEdge(edge: .ALEdgeRight, inset: 12)
firstViewLabel.ym_autoAlignAxisToSuperviewAxis(axis: .ALAxisVertical)
//不設置高度會自動布局
firstViewLabel.ym_autoSetDimensionToSize(dimension: .ALDimensionHeight, size: 20)
- 設置寬高的比例
let fisrtViewLabel2 = UILabel()
fisrtViewLabel2.text = "第二個label2"
fisrtViewLabel2.textColor = UIColor.green
firstView.addSubview(fisrtViewLabel2)
//fisrtViewLabel2的寬度與firstViewLabel的寬度一樣,高度是firstViewLabel的1.2倍,并且再同一垂直線上,頂部距離firstViewLabel的底部距離為5
fisrtViewLabel2.ym_autoMatchDimensionToDimensionOfView(dimension: .ALDimensionWidth, toDimension: .ALDimensionWidth, peerView: firstViewLabel)
fisrtViewLabel2.ym_autoMatchDimensionToDimensionOfViewWithMultiplier(dimension: .ALDimensionHeight, toDimension: .ALDimensionHeight, peerView: firstViewLabel, multiplier: 1.2)
fisrtViewLabel2.ym_autoAlignAxisToSameAxisOfView(axis: .ALAxisVertical, peerView: firstViewLabel)
fisrtViewLabel2.ym_autoPinEdgeToEdgeOfViewWithOffset(edge: .ALEdgeTop, toEdge: .ALEdgeBottom, peerView: firstViewLabel, offset: 5)
- 約束可以持有,方便后期改變約束
let secondView = UIView()
self.secondView = secondView
secondView.backgroundColor = UIColor.purple
self.view.addSubview(secondView)
///約束持有,后期動畫改變secondView的高度
self.secondViewHeightConstraint = secondView.ym_autoSetDimensionToSize(dimension: .ALDimensionHeight, size: 200)
secondView.ym_autoPinEdgeToSuperviewEdge(edge: .ALEdgeLeft, inset: 0)
secondView.ym_autoPinEdgeToSuperviewEdge(edge: .ALEdgeRight, inset: 0)
secondView.ym_autoPinEdgeToEdgeOfViewWithOffset(edge: .ALEdgeTop, toEdge: .ALEdgeBottom, peerView: firstView, offset: 10)
其他API就不一一列出來了,小伙伴們可以去下載來看看哈!有問題及時留言給我哈!盡量第一時間回復!謝謝
重要的事情再來一遍哈,下載地址