键盘在出现时会隐藏UITextView

时间:2014-12-24 10:25:29

标签: ios objective-c xcode cocoa-touch swift

我已将UIkeyboarddismissmode设置为.Interactive,我不知道如何调整UITextView的大小,以便键盘不会覆盖内容。我还有一个UIToolbar作为inputaccessory

这是我的代码。

@IBOutlet weak var textView: UITextView!

override func viewDidLoad() {
    super.viewDidLoad()

    self.addDoneButtonOnKeyboard()

    self.textView.keyboardDismissMode = .Interactive
}

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(true)

    // Add notification about keyboard
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardNotification:"), name:UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardNotification:"), name:UIKeyboardWillHideNotification, object: nil)
    //        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardFrameDidChange:"), name:UIKeyboardWillChangeFrameNotification, object: nil)
}

override func viewDidDisappear(animated: Bool) {
    super.viewDidDisappear(true)
    NSNotificationCenter.defaultCenter().removeObserver(UIKeyboardWillShowNotification)
    NSNotificationCenter.defaultCenter().removeObserver(UIKeyboardWillHideNotification)
}


// The UIToolbar

var toolbar = UIToolbar()

func addDoneButtonOnKeyboard()
{
    var doneToolbar: UIToolbar = UIToolbar(frame: CGRectMake(0, 0, 320, 44))
    doneToolbar.barStyle = UIBarStyle.Default

    var flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
    var photo: UIBarButtonItem = UIBarButtonItem(title: "Add Photo", style: UIBarButtonItemStyle.Bordered, target: self, action: Selector("photoButtonAction"))
    var done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: self, action: Selector("doneButtonAction"))

    var items = NSMutableArray()
    items.addObject(photo)
    items.addObject(flexSpace)
    items.addObject(done)

    doneToolbar.items = items
    doneToolbar.sizeToFit()

    doneToolbar.tintColor = UIColor(red: 240/225, green: 42/225, blue: 20/225, alpha: 1)
    doneToolbar.translucent = true

    self.toolbar = doneToolbar
    self.textView.inputAccessoryView = self.toolbar
}

func keyboardFrameDidChange(notification: NSNotification) {
    if let userInfo = notification.userInfo {
        var endFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue()
        var beginFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue()

        let animationCurveRawNSN = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber
        let animationCurveRaw = animationCurveRawNSN?.unsignedLongValue ?? UIViewAnimationOptions.CurveEaseInOut.rawValue
        let animationCurve:UIViewAnimationOptions = UIViewAnimationOptions(rawValue: animationCurveRaw)

        var animationDuration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0

        var newFrame = self.textView.frame
        var keyboardFrameEnd = self.view.convertRect(endFrame!, toView: nil)
        var keyboardFrameBegin = self.view.convertRect(beginFrame!, toView: nil)

        newFrame.origin.y -= (keyboardFrameBegin.origin.y - keyboardFrameEnd.origin.y)
        self.textView.frame = newFrame

        UIView.animateWithDuration(animationDuration,
            delay: NSTimeInterval(0),
            options: animationCurve,
            animations: { self.view.layoutIfNeeded() },
            completion: nil)
    }

}

上面的代码只会让textView以奇怪的方式移动,我不知道如何实现像Message应用一样的效果。

更新

func keyboardFrameEnd(notification: NSNotification) {
    if let userInfo = notification.userInfo {
        var endFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue()

        // Change contentInset
        self.textView.contentInset.bottom = endFrame!.height
        self.textView.scrollIndicatorInsets.bottom = endFrame!.height
    }
}

我将代码更改为上面的代码。但有时当我中途释放键盘时,scrollView会突然弹到底部,这非常奇怪。有什么建议吗?

2 个答案:

答案 0 :(得分:3)

UITextView是一个滚动视图。当键盘出现时你不需要调整它的大小:你应该调整它的contentInset属性,将.bottom增加键盘的高度。

答案 1 :(得分:0)

无论您是否有tabbar,都可以申请。 它可以完美地恢复键盘移动到原始位置的视图。

// Set this up in storyboard first. 
// It's a vertical spacing constraint between your text view and bottom of superview.
@IBOutlet weak var bottomSpacingConstraint: NSLayoutConstraint! 

override func viewDidLoad() {
        super.viewDidLoad()            

        //    Receive(Get) Notification
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardNotification:", name: UIKeyboardWillShowNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardNotification:", name: UIKeyboardWillHideNotification, object: nil)


        self.originalConstraint = self.keyboardHeightLayoutConstraint?.constant //for original coordinate.
}

func keyboardNotification(notification: NSNotification) {
        let isShowing = notification.name == UIKeyboardWillShowNotification

        var tabbarHeight: CGFloat = 0
        if self.tabBarController? != nil {
            tabbarHeight = self.tabBarController!.tabBar.frame.height
        }
        if let userInfo = notification.userInfo {
            let endFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue()
            let duration:NSTimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0
            let animationCurveRawNSN = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber
            let animationCurveRaw = animationCurveRawNSN?.unsignedLongValue ?? UIViewAnimationOptions.CurveEaseInOut.rawValue
            let animationCurve:UIViewAnimationOptions = UIViewAnimationOptions(rawValue: animationCurveRaw)
            self.keyboardHeightLayoutConstraint?.constant = isShowing ? (endFrame!.size.height - tabbarHeight) : self.originalConstraint!
            UIView.animateWithDuration(duration,
                delay: NSTimeInterval(0),
                options: animationCurve,
                animations: { self.view.layoutIfNeeded() },
                completion: nil)
        }
}

Move textfield when keyboard appears swift