2017-04-18 2 views
0

Ich nehme gerade diesen Kurs über Bildlauf von raywendlich. Es gibt eine Lektion darüber, wie dem Benachrichtigungscenter Beobachter hinzugefügt werden, um zu verfolgen, wann das keyBoard angezeigt wird. So sieht der Code aus.Tastatur mit Bildlaufansicht verwalten

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 
} 

Dies funktioniert korrekt, wenn das Textfeld zum ersten Mal angeklickt wird. Wenn Sie jedoch auf das Textfeld klicken, fügt es immer wieder Speicherplatz hinzu.

Würde mich über jede Hilfe freuen. :)

Antwort

0

Es ist besser, nicht "+ =" Operation zu verwenden. Die alternative Lösung könnte wie folgt aussehen:

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 
    } 

} 
Verwandte Themen