How to move content of UIViewController upwards as Keypad appears using Swift

孤街醉人 提交于 2019-12-19 05:01:35

问题


I want to move the content of the bottom of my UIViewController upwards as the keypad appears. At the bottom of the view controller I have a UITextField and when the user clicks it the keypad appears and blocks i,t so the user cannot see what they are inputting into the UITextField.

I have the UITextField declared as follows:

@IBOutlet var startTime : UITextField

Would I need a UIScrollView to accomplish this? or is there a way to move the content of the page upwards as the keypad appears.


回答1:


There are many ways to achieve this but you always need to listen to keyboard related notifications to do it. They work the same way as the obj-c ones. The following simplified example shows how to move the text field up when the keyboard appears and move it back down when it gets dismissed. The following example is an implementation of UIViewController.

override func viewDidLoad() {
    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil);
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil);
}

deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self);
}

func keyboardWillShow(sender: NSNotification) {
    let s:NSValue = sender.userInfo.valueForKey(UIKeyboardFrameEndUserInfoKey) as NSValue;
    let rect :CGRect = s.CGRectValue();
    var frame = self.textField.frame;
    frame.origin.y = frame.origin.y - rect.height;
    self.textField.frame = frame;
}

func keyboardWillHide(sender: NSNotification) {
    let s:NSValue = sender.userInfo.valueForKey(UIKeyboardFrameBeginUserInfoKey) as NSValue;
    let rect :CGRect = s.CGRectValue();
    var frame = self.textField.frame;
    frame.origin.y = frame.origin.y + rect.height;
    self.textField.frame = frame;
}



回答2:


I'm not sure how the top rated answer works; isn't it supposed to be:

func keyboardWillShow(notification: NSNotification) {
    if let info: NSDictionary = notification.userInfo {
        let value: NSValue = info.valueForKey(UIKeyboardFrameEndUserInfoKey) as NSValue
        let rect: CGRect = value.CGRectValue()
        view_comment.y = rect.height - view_comment.h
    }
}

Since you need to cast Dictionary to NSDictionary in order to access valueForkey?



来源:https://stackoverflow.com/questions/24097831/how-to-move-content-of-uiviewcontroller-upwards-as-keypad-appears-using-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!