用Swift在键盘出现时向上移动UIViewController

用Swift在键盘出现时向上移动UIViewController

本文介绍了如何使用Swift在键盘出现时向上移动UIViewController的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在键盘出现时向上移动UIViewController底部的内容。在视图控制器的底部有一个UITextField,当用户单击它时,键盘出现并阻止i,t,因此用户不能看到他们正在输入到UITextField。

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.

我有UITextField声明如下:

I have the UITextField declared as follows:

@IBOutlet var startTime : UITextField

我需要一个UIScrollView来完成这个吗?

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.

推荐答案

有很多方法可以实现这一点但是你总是需要听键盘相关的通知来做。他们的工作方式与obj-c相同。以下简化示例说明如何在键盘出现时向上移动文本字段,并在关闭时将其向下移动。以下示例是UIViewController的实现。

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;
}

这篇关于如何使用Swift在键盘出现时向上移动UIViewController的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 04:25