2017-04-18 3 views
0

現在、私はraywenderlichのスクロールビューについてこのコースを取っています。キーボードがいつ表示されるかを追跡するために、通知センターにオブザーバーを追加する方法に関するレッスンがあります。コードの外観は次のとおりです。スクロールビューのキーボードの管理

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 
    } 

} 
関連する問題