美文网首页
swift 获取ios软键盘高度,并让UITextField或U

swift 获取ios软键盘高度,并让UITextField或U

作者: 其所以然 | 来源:发表于2016-05-08 15:47 被阅读0次

    用到的变量

    @IBOutlet weak var textField: UITextField!

    var keyHeight = CGFloat() //键盘的高度

    在viewDidLoad()中声明一个监听键盘事件

    override func viewDidLoad() {

    super.viewDidLoad()

    textField.delegate = self

    let centerDefault = NSNotificationCenter.defaultCenter()

    centerDefault.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: UIKeyboardWillShowNotification, object: nil)

    }

    //完成keyboardWillShow() 

    //同时键盘弹出时上移

    func keyboardWillShow(aNotification: NSNotification) {

    let userinfo: NSDictionary = aNotification.userInfo!

    let nsValue = userinfo.objectForKey(UIKeyboardFrameEndUserInfoKey)

    let keyboardRec = nsValue?.CGRectValue()

    let height = keyboardRec?.size.height

    self.keyHeight = height! 

    UIView.animateWithDuration(0.5, animations: {

    var frame = self.view.frame

    frame.origin.y = -self.keyHeight

    self.view.frame = frame

    }, completion: nil)

    }

    //键盘隐藏时恢复

    func textFieldShouldEndEditing(textField: UITextField) -> Bool {

    UIView.animateWithDuration(0.5, animations: {

    var frame = self.view.frame

    frame.origin.y = 0

    self.view.frame = frame

    }, completion: nil)

    return true

    }

    相关文章

      网友评论

          本文标题:swift 获取ios软键盘高度,并让UITextField或U

          本文链接:https://www.haomeiwen.com/subject/yomsrttx.html