之前做項目時為了節省時間趕工期,經常用storyboard或者XIB來拖拽視圖做頁面,經常會遇到各種各樣的跟代碼不兼容的錯誤,也沒有時間靜下心來去找尋其中的問題出在哪里,最終還是決定以后用代碼布局來做項目了。
現在市面上已經有很多ios的代碼布局框架,如Masonry等等。但是對于我等手殘黨來說,用蘋果自帶的 NSLayoutConstraint 就感覺完全夠用了。但是原生的在寫起來代碼又有些復雜,所以就花了些時間對其進行了一次小封裝,主要是對 NSLayoutConstraint 和 NSLayoutAttribute 進行了整理。好了話不多少了上代碼~
完整的DEMO代碼如下:
class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let label = UILabel() label.backgroundColor = UIColor.blue label.text = "this is test" label.textColor = UIColor.yellow self.view.addSubview(label)//該方法要放到布局代碼前 label.CenterX.layout(constrain: self.view.CenterX, constant: 0) .CenterY.layout(constrain: self.view.CenterY, constant: 0) .Left.layout(constrain: self.view.Left, constant: 20) .Right.layout(constrain: self.view.Right, constant: -20) .heightLayoutConstraint(height: 80) let greenView = UIView() greenView.backgroundColor = UIColor.green self.view.addSubview(greenView) greenView.Top.layout(constrain: label.Bottom, constant: 20) .CenterX.layout(constrain: label.CenterX, constant: 0) .widthLayoutConstraint(width: 80) .heightLayoutConstraint(height: 80) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. }}運行起來是這樣的:
個人比較喜歡這種鏈式調用的敲代碼方式,當然這個小輪子目前還很不完善,承重能力有限,基本實現思路是通過協議擴展的方式對UIView 進行的功能增強~~將原生的代碼布局用到的屬性封裝成了 ConstraintClass 類。
class ConstraintClass { var view: UIView! var attribute: NSLayoutAttribute! init(view: UIView!, attribute: NSLayoutAttribute!) { self.view = view self.attribute = attribute } }然后對NSLayoutAttribute進行了封裝,目前就這么簡單啦,后面如果有更多的需求和精力的話,再完善功能??!
如果這段簡單的代碼能入得了看管的法眼,想要拿來試一試的話,歡迎去github上下載 示例代碼。 使用時只需要將DEMO項目中的Layout文件夾拖放到你自己的項目中就可以像示例中的代碼那樣使用了。另外 UIView+Extensions.swift 對 UIView 進行了一些屬性擴展,可能跟你自己寫的有沖突,使用時需要注意。
寫在最后:歡迎swift同學交流學習!!站內撕我~~
新聞熱點
疑難解答