当键盘显示时,Swift ios移动文本字段

时间:2015-06-05 13:03:51

标签: ios uitableview swift keyboard

我是ios / swift的新手,不知道在文字字段/键盘上该怎么做。

当我点击文本字段时,键盘会阻止/覆盖它,所以我无法选择它或任何其他文本字段。

那么最佳解决方案是什么?除了在滚动视图中包装所有内容之外。

我找到了这个代码段,但我不确定如何实现它:

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()
    }

或者如果某人有来自github的优秀代码示例/库,请分享:)

提前致谢,

2 个答案:

答案 0 :(得分:2)

首先,您应该注册两个键盘通知:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)

然后,您应该将文本字段嵌入UIView(我们称之为inputView)。接下来,您应该参考视图的顶部(或底部约束)。以下是具有底部约束的示例:

@IBOutlet weak var inputViewBottomConstraint: NSLayoutConstraint!

接下来,实现两个观察者函数:

func keyboardWillShow(notification : NSNotification) {

    var keyboardSize = notification.userInfo?[UIKeyboardFrameEndUserInfoKey]?.CGRectValue().size

    previousConstant = self.inputViewBottomConstraint.constant
    self.inputViewBottomConstraint.constant = keyboardSize!.height

    UIView.animateWithDuration(0.3, delay: 0, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void in
        self.layoutIfNeeded()
    })
}

func keyboardWillHide(notification : NSNotification) {

    self.inputViewBottomConstraint.constant = previousConstant
    self.layoutIfNeeded()
}

答案 1 :(得分:1)

Swift 3.0 - 如果你的textField在UITableView里面

    NotificationCenter.default.addObserver(self, selector:#selector(youViewContorllerName.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector:#selector(youViewContorllerName.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

  func keyboardWillShow(notification : NSNotification) {

        let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue.size

        self.constraintTblBottom.constant = keyboardSize.height
        UIView.animate(withDuration: 0.3, delay: 0, options: UIViewAnimationOptions.curveLinear, animations: { () -> Void in
            self.layoutIfNeeded()
        })
    }

    func keyboardWillHide(notification : NSNotification) {
        self.constraintTblBottom.constant = 0
        self.layoutIfNeeded()
    }