您的位置:首页 > 移动开发 > Swift

[iOS备忘录]UITextView多行输入,键盘隐藏问题[swift]

2015-08-21 09:47 555 查看
使用UITextView进行多行输入,输入完毕后关闭键盘

UIScrollView与UITextView配合使用,可实现多行输入。

       var msgText: UITextView!

       let sc = UIScrollView()

override func viewDidLoad() {

        super.viewDidLoad()

        let notificationCenter = NSNotificationCenter.defaultCenter()

        notificationCenter.addObserver(self, selector: "handleKeyboardWillShowNotification:", name:      

                        UIKeyboardWillShowNotification, object: nil)

        notificationCenter.addObserver(self, selector: "handleKeyboardWillHideNotification:", name:

                        UIKeyboardWillHideNotification, object: nil)

        // scroll

        sc.frame = self.view.frame

        sc.delegate = self

        sc.contentSize = CGSize(width: 250,height: 150)

        self.view.addSubview(sc);

      

        msgText = UITextView(frame: CGRectMake(10, screenHeight-100, width-20, 40))

        msgText.editable = true

        msgText.layer.masksToBounds = true

        msgText.layer.cornerRadius = 10.0

        msgText.layer.borderWidth = 1

        msgText.layer.borderColor = UIColor.lightGrayColor().CGColor

        msgText.font = UIFont.systemFontOfSize(CGFloat(20))

        self.view.addSubview(msgText)

        

        // 关闭键盘的按钮

        let accessoryView: UIView = UIView(frame: CGRectMake(0, 0, 210, 40))

        accessoryView.backgroundColor = UIColor.clearColor()

        

        let closeBtn = UIButton.buttonWithType(UIButtonType.System) as! UIButton

        closeBtn.frame = CGRectMake(210, 10, width-100, 30)

        closeBtn.setTitle("閉じる", forState: .Normal)

        closeBtn.addTarget(self, action: "closeBtnClicked", forControlEvents: UIControlEvents.TouchUpInside)

        accessoryView.addSubview(closeBtn)

        msgText.inputAccessoryView = accessoryView

        sc.addSubview(msgText)



func handleKeyboardWillShowNotification(notification: NSNotification) {

        

        let userInfo = notification.userInfo!

        let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()

        let myBoundSize: CGSize = UIScreen.mainScreen().bounds.size

        var txtLimit = msgText.frame.origin.y + msgText.frame.height + 8.0

        //var btnLimit = sendBtn.frame.origin.y + sendBtn.frame.height

        let kbdLimit = myBoundSize.height - keyboardScreenEndFrame.size.height

       

         if txtLimit >= kbdLimit {

        //if btnLimit >= kbdLimit {

            sc.contentOffset.y = btnLimit - kbdLimit

        }

    }

    

    func handleKeyboardWillHideNotification(notification: NSNotification) {

        sc.contentOffset.y = 0

    }

如果设置了按钮需要按钮与输入栏一起联动的话,需要将按钮也添加到scroll里,并修改limit(btnLimit)即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息