swift --->iOS 虚拟键盘动态添加视图

本文介绍了一个Swift UI项目中实现键盘显示隐藏时视图调整的方法。通过监听键盘展示和隐藏通知来调整视图位置,并实现了一个完成按钮帮助收起键盘。

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


import UIKit


class ViewController: UIViewController {


    @IBOutlet weak var tfd: UITextField!

    var upView :UIView = UIButton()


    override func viewDidLoad() {

        super.viewDidLoad()

        upView.frame = CGRectMake(0, self.view.frame.size.height , self.view.frame.size.width, 30.0)

        upView.backgroundColor = UIColor.lightGrayColor()

        // 创建完成”button

        let returnButton = UIButton(frame:CGRectMake(upView.bounds.size.width - 50, 0, 50, 30 ))

        returnButton.backgroundColor = UIColor.lightGrayColor()

        returnButton.setTitle("完成", forState: UIControlState.Normal)

        returnButton.addTarget(self, action: "CancelBackKeyboard", forControlEvents: UIControlEvents.TouchDown)

        upView.addSubview(returnButton)

        self.view.addSubview(upView)

        

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

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

        println(upView)

    

    }


    func handleKeyboardDidShow(notification:NSNotification) {

        var info:NSDictionary = notification.userInfo!

        var kbSize = info.objectForKey(UIKeyboardFrameEndUserInfoKey)?.CGRectValue().size

        var distanceToMove = kbSize!.height

        self.adjustKeyboardHeight(distanceToMove)

        

    }

    

    func handleKeyboardWillHide(notification:NSNotification) {

        upView.frame = CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 30.0)

        self.view.addSubview(upView)

    }

    

    func adjustKeyboardHeight(height:CGFloat) {

       upView.frame = CGRectMake(0, self.view.frame.size.height - 30 - height, self.view.frame.size.width, 30.0)

        self.view.addSubview(upView)

      

    }

    

    func CancelBackKeyboard() {

        tfd.resignFirstResponder()

    }

    

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

        tfd.resignFirstResponder()

    }

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        

    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值