好吧樱衷,我承認(rèn)今天是湊數(shù)的。
來(lái)酒唉,上圖矩桂,看gif。
keyboardCollapse.gif
這里的問(wèn)題是痪伦,鍵盤回收后侄榴,莫名的在AlertView顯示完后,再次彈出收回了网沾。
為啥會(huì)有這個(gè)問(wèn)題呢癞蚕?代碼如下,這里用的是UIAlertView(iOS9已經(jīng)不用了辉哥,不過(guò)為了兼容iOS7桦山,我們還是會(huì)用到的)。
textField.resignFirstResponder()
let alertView = UIAlertView.init(title: "Alert View", message: "test keyboard collapse", delegate: self, cancelButtonTitle: "cancel")
alertView.show()
鍵盤收回動(dòng)畫時(shí)長(zhǎng):0.25秒醋旦。
而這里我們?cè)谌∠鹴extfield的第一響應(yīng)者之后恒水,立刻彈出AlertView。相當(dāng)于打斷了鍵盤回收的動(dòng)畫饲齐。結(jié)果就是在AlertView完成后钉凌,又執(zhí)行一邊鍵盤收起的動(dòng)畫。
解決辦法:
獲取收回時(shí)間長(zhǎng)度捂人,延時(shí)該時(shí)長(zhǎng)后御雕,再?gòu)棾鯝lertView。
PS:相同的設(shè)定滥搭,用UIAlertController就不會(huì)有問(wèn)題酸纲,不知道什么原因。
修正后的代碼:
textField.resignFirstResponder()
//延時(shí)0.5秒
let time: NSTimeInterval = 0.5
let delay = dispatch_time(DISPATCH_TIME_NOW,
Int64(time * Double(NSEC_PER_SEC)))
dispatch_after(delay, dispatch_get_main_queue()) {
let alertView = UIAlertView.init(title: "Alert View",
message: "test keyboard collapse", delegate: self,
cancelButtonTitle: "cancel")
alertView.show()
}
獲取鍵盤收回動(dòng)畫時(shí)長(zhǎng)的方法:
通過(guò)通知UIKeyboardWillHideNotification论熙,來(lái)獲得鍵盤回收的信息福青。
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardHideAction:", name: UIKeyboardWillHideNotification, object: nil)
}
func keyboardHideAction(noti: NSNotification) {
let userInfo = noti.userInfo
if let animationDuration = userInfo!["UIKeyboardAnimationDurationUserInfoKey"] {
print("\(animationDuration)")
}
}
鍵盤收回的幾種方法:
- 取消textfield第一響應(yīng)者
- 取消textfield所在的父視圖的第一響應(yīng)者
//取消textfield第一響應(yīng)者
textField.resignFirstResponder()
//取消textfield所在的父視圖的第一響應(yīng)者
view.endEditing(true)
//通過(guò)UIApplication獲取當(dāng)前視圖摄狱,然后取消第一響應(yīng)者
UIApplication.sharedApplication().keyWindow?.endEditing(true)
彩蛋
運(yùn)行時(shí)屬性
我給Buuton添加了運(yùn)行時(shí)屬性脓诡,設(shè)定layer圓角。這里展示的是在XIB中設(shè)定運(yùn)行時(shí)屬性媒役。
Demo地址見這里