国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

二手輪之 Swift 純代碼布局簡化版

2019-11-06 09:44:48
字體:
來源:轉載
供稿:網友

二手輪之 Swift 純代碼布局簡化版

一、產生原因二、DEMO裝X三、原理簡介四、如何使用

產生原因

之前做項目時為了節省時間趕工期,經常用storyboard或者XIB來拖拽視圖做頁面,經常會遇到各種各樣的跟代碼不兼容的錯誤,也沒有時間靜下心來去找尋其中的問題出在哪里,最終還是決定以后用代碼布局來做項目了。

現在市面上已經有很多ios的代碼布局框架,如Masonry等等。但是對于我等手殘黨來說,用蘋果自帶的 NSLayoutConstraint 就感覺完全夠用了。但是原生的在寫起來代碼又有些復雜,所以就花了些時間對其進行了一次小封裝,主要是對 NSLayoutConstraintNSLayoutAttribute 進行了整理。好了話不多少了上代碼~

DEMO裝X

//先來看看效果(療效好才有看下去的動力),在使用時,只需要像下面這樣寫代碼就可以: 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)

完整的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.swiftUIView 進行了一些屬性擴展,可能跟你自己寫的有沖突,使用時需要注意。

寫在最后:歡迎swift同學交流學習!!站內撕我~~


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 察隅县| 胶州市| 和静县| 广饶县| 江永县| 郯城县| 清水县| 叙永县| 河北区| 珠海市| 临城县| 东阿县| 湘潭市| 丰城市| 尼玛县| 岚皋县| 临江市| 淮安市| 桑植县| 巴楚县| 临泉县| 阳西县| 遂溪县| 浦县| 克东县| 勃利县| 怀集县| 彭水| 麻阳| 岑溪市| 河池市| 合阳县| 浮梁县| 康乐县| 石狮市| 乌鲁木齐市| 桂阳县| 广南县| 克什克腾旗| 颍上县| 厦门市|