在学习开发登陆页的时候,遇到的问题分享如下:
首先是swift 3.0 中,NotificationCenter 设置 selector 如下:
@IBOutlet weak var bottomConstraint: NSLayoutConstraint! //注意这里要在storyboard对最底部的控件设置约束,然后连线到.swift文件进行绑定
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector:#selector(keyboardWillChange(notification:)),
name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
}
点击空白处取消弹出的键盘
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
键盘改变事件,防止键盘遮住输入框
// 键盘改变
func keyboardWillChange(notification: NSNotification) {
if let userInfo = notification.userInfo,
let value = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue,
let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? Double,
let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? UInt { let frame = value.cgRectValue var intersection = frame.intersection(self.view.frame)
//当键盘消失,让view回归原始位置
if intersection.height == 0.0 {
intersection = CGRect(x: intersection.origin.x, y: intersection.origin.y, width: intersection.width, height: )
}
UIView.animate(withDuration: duration, delay: 0.0,
options: UIViewAnimationOptions(rawValue: curve), animations: {
_ in
//改变下约束
self.bottomConstraint.constant = intersection.height
self.view.layoutIfNeeded()
}, completion: nil)
}
}
后续肯定还会遇到很多问题,我会尽量把我遇到的问题以及解决办法记录下来供后来者学习。
顺便吐槽一下,从安卓转过来,发现好多问题给出的解决方案都是 Object-C ,而且 Swift 版本更迭,变化很大,网上很多的解决方案经常需要自己微小调动才能正常使用。给我这样的新手带来好多麻烦。
注:开发环境是Xcode 8.1 测试平台是 iOS 10.0