2017-04-18 75 views
0

我目前采取这一过程大约滚动查看从raywenderlich。有关于如何将观察员添加到通知中心以跟踪keyBoard何时显示的教训。这是代码的外观。管理键盘,滚动视图

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: .UIKeyboardWillShow, object: nil) 
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: .UIKeyboardWillHide, object: nil) 


func keyboardWillHide(notification: Notification) { 
    adjustKeyboardInset(false, notification: notification) 
} 

func keyboardWillShow(notification: Notification) { 
    adjustKeyboardInset(true, notification: notification) 
} 

func adjustKeyboard(isShown: Bool, notification: Notification) { 
    let userInfo = notification.userInfo ?? [:] 
    let keyboardFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue 

    let adjustedHeight = keyboardFrame.height * (isShown ? 1 : -1) + 20 

    mySV.contentInset.bottom += adjustedHeight 
    mySV.scrollIndicatorInsets.bottom += adjustedHeight 
} 

这工作正常,第一次点击的文本字段。但是,当你继续点击textField时,它会不断增加空间。

希望有任何帮助。 :)

回答

0

这是最好不要使用 “+ =” 操作。该替代的解决方案可能是这样的:

var originalBottom:CGFloat = 0.0 
var originalIndicatorBottom:CGFloat = 0.0 

override func viewDidLoad() { 
    super.viewDidLoad() 
    originalBottom = mySV.contentInset.bottom.constant 
    originalIndicatorBottom:CGFloat = mySV.scrollIndicatorInsets.bottom.constant 
} 

//......  

func adjustKeyboard(isShown: Bool, notification: Notification) { 
    let userInfo = notification.userInfo ?? [:] 
    let keyboardFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue 

    let adjustedHeight = keyboardFrame.height + 20 

    if isShown { 
     mySV.contentInset.bottom = originalBottom + adjustedHeight 
     mySV.scrollIndicatorInsets.bottom = originalIndicatorBottom + adjustedHeight 
    } 
    else 
    { 
     mySV.contentInset.bottom = originalBottom 
     mySV.scrollIndicatorInsets.bottom = originalIndicatorBottom 
    } 

} 
相关问题