如何自动滚动选择UItextfield然后点击返回更改位置视图?

时间:2016-03-15 07:13:48

标签: swift uitextfield

//选择UItextfield时自动滚动的代码。

func textFieldDidBeginEditing(textField: UITextField) {
    self.scrollView.contentOffset = CGPointMake(0, textField.frame.origin.y - 10);
}

func textFieldDidEndEditing(textField: UITextField) {
    self.scrollView.contentOffset = CGPointMake(0, textField.frame.origin.y - textField.frame.origin.y);
}

2 个答案:

答案 0 :(得分:0)

您可以使用textField委托方法textFieldShouldReturn并考虑以下示例:

func textFieldShouldReturn(textField: UITextField) -> Bool {

    //set setContentOffset here
    self.scrollView.setContentOffset(CGPointMake(0, 0), animated: true)
    self.view.endEditing(true)
    return true
}

希望这会有所帮助。

答案 1 :(得分:0)

在按下文本字段时滚动视图(键盘已启动),您必须在键盘状态下添加NSNotificationCenter观察者。 只需在viewDidLoad()

中添加这两行
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)

然后添加函数以相应地更改self.view.frame.origin.y

func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
            self.view.frame.origin.y -= keyboardSize.height
    }
}

func keyboardWillHide(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
            self.view.frame.origin.y += keyboardSize.height
    }
}