使用swift时,文本字段会在键盘出现时向上移动

时间:2014-12-04 15:28:44

标签: ios swift xcode6

在目标C中,这两行简单代码用于向上滚动文本视图。 SWIFT中是否有任何简单的代码向上滚动文本字段?请帮助我。

- (void)textFieldDidBeginEditing:(UITextField *)textField {
CGPoint scrollPoint = CGPointMake(0, textField.frame.origin.y);
[scrollView setContentOffset:scrollPoint animated:YES];
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
[scrollView setContentOffset:CGPointZero animated:YES];
}

4 个答案:

答案 0 :(得分:0)

on:

UITextFieldTextDidEndEditingNotificationUITextFieldTextDidBeginEditingNotification

调用此方法为文本字段设置动画

UIView.animateWithDuration(yourTime, delay: 0, options: .CurveEaseOut, animations: {
yourTextField.frame = yourNewFrame
}, completion: { finished in
println("Basket doors opened!")
})

希望这有帮助!

答案 1 :(得分:0)

最好使用它:

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        scrollView.scrollEnabled = true
    yourTextfield.addTarget(self, action: "textFieldShouldReturn:", forControlEvents: .EditingDidEndOnExit)
    yourTextfield2.addTarget(self, action: "textFieldShouldReturn:", forControlEvents: .EditingDidEndOnExit)
    ...


    yourTextfield.tag = 1
    yourTextfield2.tag = 2
    ...
}   

    func textFieldShouldReturn(textField: UITextField!) -> Bool {
            let nextTag = textField.tag + 1
            let nextResponder:UIResponder? = textField.superview?.viewWithTag(nextTag)
            if ((nextResponder) != nil) {
                nextResponder?.becomeFirstResponder()
                var scrollPoint: CGPoint = CGPointMake(0, textField.frame.origin.y - 50)
                scrollView.setContentOffset(scrollPoint, animated: true)
            } else {
                textField.resignFirstResponder()
                scrollView.setContentOffset(CGPointZero, animated: true)
            }
            return false
        }

答案 2 :(得分:0)

设置文本字段的委托并实现以下方法

func textFieldDidBeginEditing(textField: UITextField) {
        animateViewMoving(true, moveValue: 100)
}
func textFieldDidEndEditing(textField: UITextField) {
        animateViewMoving(false, moveValue: 100)
}

func animateViewMoving (up:Bool, moveValue :CGFloat){
    var movementDuration:NSTimeInterval = 0.3
    var movement:CGFloat = ( up ? -moveValue : moveValue)
    UIView.beginAnimations( "animateView", context: nil)
    UIView.setAnimationBeginsFromCurrentState(true)
    UIView.setAnimationDuration(movementDuration )
    self.view.frame = CGRectOffset(self.view.frame, 0,  movement)
    UIView.commitAnimations()
}

参考:https://stackoverflow.com/a/32755167/988169

答案 3 :(得分:0)

你可以用这种方式编写代码 -

let biginSel = #selector(LoginViewController.didBeginEditing(_:))
    NSNotificationCenter.defaultCenter().addObserver(self, selector: biginSel, name: UITextFieldTextDidBeginEditingNotification, object: usrNmFld)