ios swift开发中,使用键盘,tableview根据键盘调整高度

本文介绍了在iOS Swift应用中,如何监听并响应键盘显示和隐藏事件,动态调整TableView的高度,确保键盘弹出时不会遮挡输入框。通过在`viewDidLoad`中注册键盘通知,并实现`keyboardWillShow`和`keyboardWillHide`方法来改变TableView的frame,从而实现键盘出现时自动滚动到合适位置。同时在`viewWillDisappear`中移除键盘通知,避免内存泄漏。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.在viewdidload中,注册如下监听:

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

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


2. 实现对应的监听触发方法:

    func keyboardWillShow(note:NSNotification){

        var userInfo:NSDictionary = note.userInfo!

        var aValue:NSValue = userInfo.objectForKey("UIKeyboardFrameEndUserInfoKey") as! NSValue

        var keyboardRect:CGRect = aValue.CGRectValue()

        keyboardRect = self.view.convertRect(keyboardRect, fromView: nil)

        var keyboardTop:CGFloat = keyboardRect.origin.y

        var newTextViewFrame:CGRect = self.view.bounds

        newTextViewFrame.size.height = keyboardTop - self.view.bounds.origin.y

        var animationDurationValue:NSValue = userInfo.objectForKey("UIKeyboardAnimationDurationUserInfoKey") as! NSValue

        var  animationDuration:NSTimeInterval? = 0.5

        animationDurationValue.getValue(&animationDuration)

        UIView.beginAnimations(nil, context: nil)

        UIView.setAnimationDuration(animationDuration!)

        self._chatView.frame = newTextViewFrame

        UIView.commitAnimations()

    }

    

    func keyboardWillHide(note:NSNotification){

        var userInfo:NSDictionary = note.userInfo!

        var animationDurationValue:NSValue = userInfo.objectForKey("UIKeyboardAnimationDurationUserInfoKey") as! NSValue

        var  animationDuration:NSTimeInterval? = 0.5

        animationDurationValue.getValue(&animationDuration)

        UIView.beginAnimations(nil, context: nil)

        UIView.setAnimationDuration(animationDuration!)

        self._chatView.frame = self.view.bounds;

        UIView.commitAnimations()

    }


3.界面退出时,卸载监听,在

    override func viewWillDisappear(animated: Bool) {

        super.viewWillDisappear(animated)

        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)

        NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)

    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值