Textfield向上滚动不起作用的iOS

时间:2017-06-23 14:49:53

标签: ios swift3

我是stackoverflow的新手。

我试图在编辑时让UI文本字段向上滚动。

这是我的代码。

import UIKit

 public class LoginViewController: UIViewController, UITextFieldDelegate {


public var loginData = userModel()



@IBOutlet weak var user: UITextField!


@IBOutlet weak var passTextField: UITextField!






override public func viewDidLoad() {
    super.viewDidLoad()



}

override public func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)


    user.delegate = self
    user.returnKeyType = .done
    self.view.addSubview(user)

    passTextField.delegate = self
    passTextField.returnKeyType = .done
    self.view.addSubview(passTextField)
}


public func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
    user.resignFirstResponder()
    passTextField.resignFirstResponder()
    return true
}


override public func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}

override public func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    loginData.login = user.text!


    var tabBar: SunnybrookTabBarController = segue.destination as! SunnybrookTabBarController


    tabBar.loginData = loginData




}

public func textFieldDidBeginEditing(_ textField: UITextField) {
    animateViewMoving(up: true, moveValue: 100)
}

public func textFieldDidEndEditing(_ textField: UITextField) {
    animateViewMoving(up: false, moveValue: 100)
}

// Lifting the view up
public func animateViewMoving (up:Bool, moveValue :CGFloat){
    let movementDuration:TimeInterval = 0.3
    let movement:CGFloat = ( up ? -moveValue : moveValue)
    UIView.beginAnimations( "animateView", context: nil)
    UIView.setAnimationBeginsFromCurrentState(true)
    UIView.setAnimationDuration(movementDuration )
    self.view.frame = self.view.frame.offsetBy(dx: 0,  dy: movement)
    UIView.commitAnimations()
}







}

现在当我实现这个时,文本字段一直被推到屏幕顶部,然后我甚至点击它们打开键盘。

As you can see they are pushed all the way from their normal placement.

1 个答案:

答案 0 :(得分:0)

将您的视图声明为@IBOutlets很可能意味着它们已经是视图层次结构的一部分。

尝试从-viewWillAppear中删除view.addSubview(view):

这可以解决您的问题。