How to make textFields stay in place when keyboard moves up? Swift

后端 未结 2 1138
失恋的感觉
失恋的感觉 2021-01-07 09:45

I have created a form with 4 fields and one button. The view hierarchy looks like this: Main UIVIew, View (renamed contentView), on top of contentView I have 4 fields and 1

2条回答
  •  粉色の甜心
    2021-01-07 10:11

    I think you should only move the fields up if they are covered by the keyboard, something like what i cooked up a couple of days ago:

    let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue ?? NSValue()).cgRectValue
    let keyboardViewEndFrame = view.convert(keyboardScreenEndFrame, from: view.window)
    UIView.animate(withDuration: 0.2) {
        if notification.name == Notification.Name.UIKeyboardWillHide {
            self.view.frame = CGRect(x: 0, y: 0, width: self.view.width, height: self.view.height)
        } else {
            let offset = (self.view.frame.size.height - self.activeField.frame.maxY) - keyboardViewEndFrame.height
            if offset < 0 {
                self.view.frame = CGRect(x: 0, y:  offset, width: self.view.width, height: self.view.height)
            } else {
                self.view.frame = CGRect(x: 0, y: 0, width: self.view.width, height: self.view.height)
            }
        }
    }
    

    Basically you just need to add logic for keyboard handling timing, and you should handle it if keyboard frame goes over textfield frame. Hope it helps.

提交回复
热议问题