寫在前面(Github地址)
主要記錄了竟稳,我在學(xué)習(xí)Snapkit中的一些整理記錄
學(xué)習(xí)目標(biāo)
好好學(xué)習(xí)如何用代碼來做自動(dòng)布局
使用SnapKit做了一個(gè)修改密碼的表單
效果圖
- Snapkit的安裝
Cocoapods安裝
在項(xiàng)目的Podfile下添加如下信息
在終端中執(zhí)行:pod install(注意路徑是當(dāng)前項(xiàng)目中Podfile鎖在路徑)
swiftsource'https://github.com/CocoaPods/Specs.git'platform :ios,'8.0'use_frameworks!pod'SnapKit','~> 0.15.0'
Carthage安裝
Carthage是一種分散式依賴管理庫用來自動(dòng)為你的Cocoa應(yīng)用添加第三方框架
1) 通過下面命令行執(zhí)行安裝Carthage
swiftbrewupdatebrewinstallcarthage
2) 通過下面命令行繼承SnapKit到你的項(xiàng)目中的Cartfile
swiftgithub"SnapKit/SnapKit">=0.15.0
3.)通過直接講SnapKit的源代碼拖放到自己的項(xiàng)目目錄當(dāng)中
這也是我比較喜歡的一種方式,這樣可以比較自由的講代碼拖放到自己執(zhí)行的目錄下
-
SnapKit的兼容操作
如果希望SnapKit支持IOS7版本玄货,需要在自己的項(xiàng)目的 Build Setting 中搜索的 OTHER_SWIFT_FLAGS,在其下面添加 -DSNAPKIT_DEPLOYMENT_LEGACY鱼冀,如下圖所示:(否則會(huì)報(bào)錯(cuò)r悸肌)
示意圖
- Snapkit官方文檔翻譯
通用模式:
swiftletbox =UIView()superview.addSubview(box)box.snp_makeConstraints { (make) ->Voidin//解釋:box對(duì)象相對(duì)于父視圖上邊距為20像素make.top.equalTo(superview).offset(20) make.left.equalTo(superview).offset(20) make.bottom.equalTo(superview).offset(-20) make.right.equalTo(superview).offset(-20)}
注意:在SnapKit當(dāng)中 X軸向右方向;Y軸向下方向 為正
縮寫形式
swiftlet box = UIView()superview.addSubview(box)box.snp_makeConstraints { (make) -> Void in//注釋:box距離父
視圖上下左右邊距都是20像素make.edges.equalTo(superview).inset(UIEdgeInsetsMake(20,20,20,20))}
SnapKit還可以通過下面幾個(gè)步驟來實(shí)現(xiàn)縮短代碼和提高代碼可讀性
確定最佳的普通視圖安裝限制嘿辟。
保持軌道的約束安裝所以他們可以很容易地被刪除后舆瘪。
在所有適當(dāng)?shù)囊晥D上確保setTranslatesAutoresizingMaskIntoConstraints(false)屬性被設(shè)置
SnapKit中并不局限于 等于(equalTo)
.equalTo:等于
.lessThanOrEqualTo 小于等于
.greaterThanOrEqualTo 大于等于
1.視圖屬性
//當(dāng)前視圖對(duì)象的中心x坐標(biāo)小于等于view視圖的左邊的x左邊make.centerX.lessThanOrEqualTo(view.snp_left)
視圖屬性:
上 :上邊對(duì)應(yīng)的Y軸 (top)
下: 下邊對(duì)應(yīng)的Y軸 (bottom)
左: 左邊對(duì)應(yīng)的Y軸 (left)
右: 右邊對(duì)應(yīng)的X軸 (right)
視圖屬性(ViewAttribute)布局屬性 (NSLayoutAttribute)
view.snp_leftNSLayoutAttribute.Left
view.snp_rightNSLayoutAttribute.Right
view.snp_topNSLayoutAttribute.Top
view.snp_bottomNSLayoutAttribute.Bottom
view.snp_leadingNSLayoutAttribute.Leading
view.snp_trailingNSLayoutAttribute.Trailing
view.snp_widthNSLayoutAttribute.Width
view.snp_heightNSLayoutAttribute.Height
view.snp_centerXNSLayoutAttribute.CenterX
view.snp_centerYNSLayoutAttribute.CenterY
view.snp_baselineNSLayoutAttribute.Baseline
2.視圖關(guān)系(UIView/NSView)
如果你想 視圖 view.left 大于等于 label.left ,執(zhí)行下面代碼:
swift//下面這兩者的約束是完全一樣的make.left.greaterThanOrEqualTo(label)make.left.greaterThanOrEqualTo(label.snp_left)
3.嚴(yán)格檢測(cè)(Strick Checks)
自動(dòng)布局允許將寬度和高度屬性設(shè)置為常量值红伦。如果你想對(duì)視圖設(shè)置一個(gè)最小和最大寬度英古,你必須先給他一個(gè)初始的平等塊:
設(shè)置寬度>= 200 && <= 400
你也可以用其他的約束和結(jié)構(gòu)來建立你的約束,像這樣:
swiftmake.top.equalTo(42)make.height.equalTo(20)make.size.equalTo(CGSizeMake(50,100))make.edges.equalTo(UIEdgeInsetsMake(10,0,10,0))make.left.equalTo(view).offset(UIEdgeInsetsMake(10,0,10,0))
4.學(xué)習(xí)優(yōu)先級(jí)
.priority: 允許您指定一個(gè)確切的優(yōu)先級(jí)
.priorityHigh: 高優(yōu)先級(jí) 等價(jià)于 UILayoutPriority.DefaultHigh
.priorityMedium:中優(yōu)先級(jí)
.priorityLow:低優(yōu)先級(jí) UILayoutPriority.DefaultLow
優(yōu)先級(jí)可以放在約束鏈的結(jié)束處昙读,例如
swift//當(dāng)前視圖的左邊>=label的底部 低優(yōu)先級(jí)make.left.greaterThanOrEqualTo(label.snp_left).priorityLow()//當(dāng)前視圖與label的頂部齊平召调,優(yōu)先級(jí):600make.top.equalTo(label.snp_top).priority(600)
5.組成,組成蛮浑,組成
SnapKit 也可以提供一些便利的方法來同時(shí)創(chuàng)建多約束
edges(邊緣)
swift//讓當(dāng)前視圖 的 上下左右(top,left,bottom,right) 等于 view2make.edges.equalTo(view2)// make top = superview.top + 5; left = superview.left +10// bottom = superview.bottom -15; right = superview.right - 20make.edges.equalTo(superView).inset(UIEdgeInsetsMake(5,10,15,20))
2.size(尺寸)
swift//當(dāng)前視圖寬高 >= titleLabelmake.size.greaterThanOrEqualTo(titleLabel)//make width = superview.width + 100; height = superview.height -50//即 當(dāng)前視圖寬 = 父視圖 + 100唠叛,高 = 父視圖.高 - 50make.size.equalTo(superview).offset(CGSizeMake(100, -50))
3.center(中心)
swift//當(dāng)前視圖與 button1中心相同 (centerX 和 centerY)make.center.equalTo(button1)//make centerX = superview.centerX - 5; centerY = superview.centerY +10make.center.equalTo(superview).offset(CGPointMake(-5,10))
您可以串連視圖屬性增加可讀性
swift//所有邊緣除了top都等于父視圖, top為20make.left.right.bottom.equalTo(superview)make.top.equalTo(20)
6.Hold on for dear life
有時(shí)候你需要修改已經(jīng)存在的約束為了移動(dòng)或者移除、代替約束沮稚。在SnapKit 有一些不同的方法更新約束
1.引用(References)
你可以通過將約束的結(jié)果賦值給一個(gè)局部變量或一個(gè)類屬性來保持一個(gè)特定的約束的引用艺沼。您還可以將多個(gè)約束引用存儲(chǔ)在數(shù)組中。
swiftvartopConstraint:Constraint? =nil//當(dāng)制作約束時(shí)view1.snp_makeConstraints{ (make) ->Voidinself.topConstrain = make.top.equalTo(superview).offset(padding.top).constraint make.left.equalTo(superview).offset(padding.left)// 然后接下來你可以這樣self.topConstraint.uninstall()//或者如果你想要更新約束self.topConstraint.updateOffset(5)
2.snp_updateConstraints(更新約束)
如果你僅僅想更新一個(gè)常數(shù)給一個(gè)約束蕴掏,你可以使用方法snp_updateConstraints來代替snp_makeConstraints
swift//這是一個(gè)蘋果官方推薦的添加和更新約束的地方//這個(gè)方法在響應(yīng)setNeedsUpdateConstraints
多次調(diào)用//這個(gè)方法可以倍UIKit調(diào)用overridefuncupdateConstraints(){self.growingButton.snp_updateConstraints{ (make) ->Voidinmake.center.equalTo(self); make.width.equalTo(self.buttonSize.width).priorityLow() make.height.equalTo(self.buttonSize.height).priorityLow() make.width.lessThanOrEqualTo(self) make.height.lessThanOrEqualTo(self) }//父類可以調(diào)用super.updateConstraints()}
3.snp_remakeConstraints(重做約束)
snp_remakeConstraints與snp_makeConstraints類似障般,但是首先會(huì)先清除掉所有被SnapKit設(shè)置的約束
swiftfuncchangeButtonPosition(){self.button.snp_remakeConstraints{ (make) ->Voidinmake.size.equalTo(self.buttonSize)iftopLeft { make.top.left.equalTo(10) }else{ make.bottom.equalTo(self.view).offset(-10) make.right.equalTo(self.view).offset(-10) } }}
4.Demo的具體代碼(我的Github)
創(chuàng)建屬性
swiftvaroldPassword:UITextField!varnewPassword:UITextField!varconfirmPassword:UITextField!varformView:UIView!varconfirmButton:UIButton!vartopConstraint:Constraint?
UI初始化
swift func initUI(){self.title="修改密碼"self.view.backgroundColor=UIColor.redColor()//登錄框背景self.formView=UIView()self.formView.layer.borderWidth=0.5self.formView.layer.borderColor=UIColor.lightGrayColor().CGColorself.formView.backgroundColor=UIColor.whiteColor()self.formView.layer.cornerRadius=5self.view.addSubview(self.formView)//最常規(guī)的設(shè)置模式self.formView.snp_makeConstraints{ (make) -> Voidinmake.left.equalTo(15) make.right.equalTo(-15)//存儲(chǔ)top屬性self.topConstraint= make.top.equalTo(200).constraintmake.height.equalTo(220) }//密碼圖let imgLock1 =UIImageView(frame:CGRectMake(11,11,22,22)) imgLock1.image=UIImage(named:"iconfont-password")//密碼圖let imgLock2 =UIImageView(frame:CGRectMake(11,11,22,22)) imgLock2.image=UIImage(named:"iconfont-password")//密碼圖let imgLock3 =UIImageView(frame:CGRectMake(11,11,22,22)) imgLock3.image=UIImage(named:"iconfont-password")//舊密碼輸入框self.oldPassword=UITextField()self.oldPassword.delegate=selfself.oldPassword.tag=100self.oldPassword.placeholder="請(qǐng)輸入舊密碼"self.oldPassword.layer.cornerRadius=5self.oldPassword.layer.borderColor=UIColor.lightGrayColor().CGColorself.oldPassword.layer.borderWidth=0.5self.oldPassword.leftView=UIView(frame:CGRectMake(0,0,44,44))self.oldPassword.leftViewMode=UITextFieldViewMode.Alwaysself.oldPassword.returnKeyType=UIReturnKeyType.Next//密碼輸入框左側(cè)圖標(biāo)self.oldPassword.leftView!.addSubview(imgLock1)self.formView.addSubview(self.oldPassword)//布局self.oldPassword.snp_makeConstraints{ (make) -> Voidinmake.left.equalTo(30) make.top.equalTo(20) make.right.equalTo(-30) make.height.equalTo(44) }//新密碼輸入框self.newPassword=UITextField()self.newPassword.delegate=selfself.newPassword.tag=101self.newPassword.placeholder="請(qǐng)輸入新密碼"self.newPassword.layer.cornerRadius=5self.newPassword.layer.borderColor=UIColor.lightGrayColor().CGColorself.newPassword.layer.borderWidth=0.5self.newPassword.leftView=UIView(frame:CGRectMake(0,0,44,44))self.newPassword.leftViewMode=UITextFieldViewMode.Alwaysself.newPassword.returnKeyType=UIReturnKeyType.Next//密碼輸入框左側(cè)圖標(biāo)self.newPassword.leftView!.addSubview(imgLock2)self.formView.addSubview(self.newPassword)//布局self.newPassword.snp_makeConstraints{ (make) -> Voidinmake.left.equalTo(30) make.top.equalTo(self.oldPassword.snp_bottom).offset(20) make.right.equalTo(-30) make.height.equalTo(44) }//確認(rèn)新密碼輸入框self.confirmPassword=UITextField()self.confirmPassword.delegate=selfself.confirmPassword.tag=102self.confirmPassword.placeholder="請(qǐng)重復(fù)新密碼"self.confirmPassword.layer.cornerRadius=5self.confirmPassword.layer.borderColor=UIColor.lightGrayColor().CGColorself.confirmPassword.layer.borderWidth=0.5self.confirmPassword.leftView=UIView(frame:CGRectMake(0,0,44,44))self.confirmPassword.leftViewMode=UITextFieldViewMode.Alwaysself.confirmPassword.returnKeyType=UIReturnKeyType.Done//密碼輸入框左側(cè)圖標(biāo)self.confirmPassword.leftView!.addSubview(imgLock3)self.formView.addSubview(self.confirmPassword)//布局self.confirmPassword.snp_makeConstraints{ (make) -> Voidinmake.left.equalTo(30) make.top.equalTo(self.newPassword.snp_bottom).offset(20) make.right.equalTo(-30) make.height.equalTo(44) }self.confirmButton=UIButton()self.confirmButton.setTitle("確認(rèn)修改", forState:UIControlState.Normal)self.confirmButton.setTitleColor(UIColor.whiteColor(), forState:UIControlState.Normal)self.confirmButton.layer.cornerRadius=5self.confirmButton.backgroundColor=UIColor(colorLiteralRed:0.99, green:0.82, blue:0.04, alpha:1)self.view.addSubview(self.confirmButton)self.confirmButton.snp_makeConstraints{ (make) -> Voidinmake.left.equalTo(15) make.top.equalTo(self.formView.snp_bottom).offset(20) make.right.equalTo(-15) make.height.equalTo(44) } }
UITextField的代理
swiftextensionSnapkitViewController:UITextFieldDelegate{//輸入框獲取焦點(diǎn)開始編輯functextFieldDidBeginEditing(textField:UITextField){lettag = textField.tagswitchtag {case100:UIView.animateWithDuration(0.5, animations: { () ->Voidinself.topConstraint?.updateOffset(150)self.view.layoutIfNeeded() })case101:UIView.animateWithDuration(0.5, animations: { () ->Voidinself.topConstraint?.updateOffset(100)self.view.layoutIfNeeded() })case102:UIView.animateWithDuration(0.5, animations: { () ->Voidinself.topConstraint?.updateOffset(70)self.view.layoutIfNeeded() })default:print("error") } }//輸入框返回時(shí)操作functextFieldShouldReturn(textField:UITextField)->Bool{lettag = textField.tagswitchtag {case100:self.newPassword.becomeFirstResponder()case101://下一個(gè)self.confirmPassword.becomeFirstResponder()case102://收起鍵盤textField.resignFirstResponder()UIView.animateWithDuration(0.5, animations: { () ->Voidinself.topConstraint?.updateOffset(200)self.view.layoutIfNeeded() })default:print(textField.text) }returntrue}}
5.總結(jié)一下 UITextField
樣式
swiftUITextBorderStyle.None:無邊框UITextBorderStyle.Line:直線邊框UITextBorderStyle.RoundedRect:圓角矩形邊框UITextBorderStyle.Bezel:邊線+陰影
輸入提示
textField.placeholder="請(qǐng)輸入用戶名"
內(nèi)容設(shè)置
swift//當(dāng)文字超出文本框?qū)挾葧r(shí),自動(dòng)調(diào)整文字大小textField.adjustsFontSizeToFitWidth =true//最小可縮小的字號(hào)textField.minimumFontSize =14
對(duì)齊方式
swift//水平右對(duì)齊textField.textAlignment = .Right//水平居中對(duì)齊textField.textAlignment = .Center//水平左對(duì)齊textField.textAlignment = .Left//垂直向上對(duì)齊textField.contentVerticalAlignment = .Top//垂直居中對(duì)齊textField.contentVerticalAlignment = .Center//垂直向下對(duì)齊textField.contentVerticalAlignment = .Bottom
設(shè)置清除按鈕
swift//編輯時(shí)出現(xiàn)清除按鈕textField.clearButtonMode=UITextFieldViewMode.WhileEditing//編輯時(shí)不出現(xiàn)盛杰,編輯后才出現(xiàn)清除按鈕textField.clearButtonMode=UITextFieldViewMode.UnlessEditing//一直顯示清除按鈕textField.clearButtonMode=UITextFieldViewMode.Always
設(shè)置鍵盤的類型
swiftDefault:系統(tǒng)默認(rèn)的虛擬鍵盤ASCII Capable:顯示英文字母的虛擬鍵盤Numbers and Punctuation:顯示數(shù)字和標(biāo)點(diǎn)的虛擬鍵盤URL:顯示便于輸入數(shù)字的虛擬鍵盤NumberPad:顯示便于輸入數(shù)字的虛擬鍵盤Phone Pad:顯示便于撥號(hào)呼叫的虛擬鍵盤Name Phone Pad:顯示便于聊天撥號(hào)的虛擬鍵盤Email Address:顯示便于輸入Email的虛擬鍵盤DecimalPad:顯示用于輸入數(shù)字和小數(shù)點(diǎn)的虛擬鍵盤Twitter:顯示方便些Twitter的虛擬鍵盤Web Search:顯示便于在網(wǎng)頁上書寫的虛擬鍵盤//例子textField.keyboardType = UIKeyboardType.NumberPad
焦點(diǎn)
swift//獲取焦點(diǎn)textField.becomeFirstResponder()//移除焦點(diǎn)textField.resignfirstresponder()
設(shè)置返回return樣式跟功能
swift//表示完成輸入textField.returnKeyType=UIReturnKeyType.Done//表示完成輸入挽荡,同時(shí)會(huì)跳到另一頁textField.returnKeyType=UIReturnKeyType.Go//表示搜索textField.returnKeyType=UIReturnKeyType.Search//表示注冊(cè)用戶或添加數(shù)據(jù)textField.returnKeyType=UIReturnKeyType.Join//表示繼續(xù)下一步textField.returnKeyType=UIReturnKeyType.Next//表示發(fā)送textField.returnKeyType=UIReturnKeyType.Send
代理
swift//開始編輯時(shí)的操作functextFieldDidBeginEditing()//點(diǎn)擊返回按鈕時(shí)的操作functextFieldShouldReturn()
轉(zhuǎn)載自:Swift編程(六):Snapkit的啟示錄 - 簡(jiǎn)書