我们如何让键盘出现在swift中的textView下面?

时间:2017-11-07 06:12:37

标签: swift swift3 swift2

我使用

键盘出现在textfield下方

on View确实加载了观察者()

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(Gold_Loan_First_ViewController.keyboardDidShow(_:)), name: UIKeyboardDidShowNotification, object: nil)

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(Gold_Loan_First_ViewController.keyboardWillBeHidden(_:)), name: UIKeyboardWillHideNotification, object: nil)

然后更新框架

weak var activeField: UITextField?

func textFieldDidEndEditing(textField: UITextField) {
    self.activeField = nil


}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if textField==txtOTP {
        txtOTP.errorMessage=""
    }
  return true
}
func textFieldDidBeginEditing(textField: UITextField) {
    self.activeField = textField

}




func keyboardDidShow(notification: NSNotification)
{
    if let activeField = self.activeField,
        let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
        let contentInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize.height, right: 0.0)
        self.scrollView.contentInset = contentInsets
        self.scrollView.scrollIndicatorInsets = contentInsets
        var aRect = self.view.frame
        aRect.size.height -= keyboardSize.size.height
        if (!CGRectContainsPoint(aRect, activeField.frame.origin)) {
            self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
        }
    }


}

func keyboardWillBeHidden(notification: NSNotification)
{
    let contentInsets = UIEdgeInsetsZero
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
}

但我如何为textView做到这一点。我用textView的didBeginEditing尝试了相同的代码而没有任何正面效果

5 个答案:

答案 0 :(得分:4)

简单易行的解决方案之一是在您的应用中使用以下播客。

IQKeyboardManger

稍后你需要在App Delegate中导入它,并在didfinishLaunching方法中添加这两行代码:

  IQKeyboardManager.sharedManager().enable = true

您的问题将在整个应用中解决。

答案 1 :(得分:1)

我经历过这样的情况。首先,我在UiViewController中添加了扩展程序:

    extension CCViewController : UITextViewDelegate {
        func textViewDidBeginEditing(_ textView: UITextView) {
            // write code as per your requirements
        }

        func textViewDidEndEditing(_ textView: UITextView) {
             // write code as per your requirements
        }

        func textViewDidChange(_ textView: UITextView) {
            self.p_adjustMessageFieldFrameForTextView(textView)
        }
    }

    // Defining the p_adjustMessageFieldFrameForTextView method

    fileprivate func p_adjustMessageFieldFrameForTextView(_ textView : UITextView) {
            var finalheight : CGFloat = textView.contentSize.height + 10
            var kMaxMessageFieldHeight : CGFloat = 50
            if  (finalheight > kMaxMessageFieldHeight) {
                finalheight = kMaxMessageFieldHeight;
            } else if (finalheight < kCommentTextViewHeight){
                finalheight = kCommentTextViewHeight;
            }

            scrollView!.view.frame = CGRect(x: 0, y: kNavBarHeight + statuBarHeight, width: SCREEN_WIDTH,height: SCREEN_HEIGHT - finalheight - keyboardRect!.size.height - kNavBarHeight - statuBarHeight)
// It is there for understanding that we have to calculate the exact frame of scroll view

            commentTextView!.frame = CGRect(x: 0, y: bottomOfView(scrollView!.view), width: SCREEN_WIDTH, height: finalheight)
            self.p_setContentOffsetWhenKeyboardIsVisible()
        }

    // Defining the p_setContentOffsetWhenKeyboardIsVisible method

    fileprivate func p_setContentOffsetWhenKeyboardIsVisible() {
            // here you can set the offset of your scroll view
        }

还有一个名为bottomView()的方法:

func bottomOfView(_ view : UIView) -> CGFloat {
        return view.frame.origin.y + view.frame.size.height
    }

答案 2 :(得分:1)

Salman Ghumsani是对的。

请将UIKeyboardFrameBeginUserInfoKey更改为UIKeyboardFrameEndUserInfoKey

Apple Debeloper Document: Keyboard Notification User Info Keys

<强> UIKeyboardFrameEndUserInfoKey

包含CGRect的NSValue对象的键,该CGRect在屏幕坐标中标识键盘的ending框架矩形。框架矩形反映了设备的当前方向。

<强> UIKeyboardFrameBeginUserInfoKey

关键 NSValue  包含a的对象 的CGRect  在屏幕坐标中标识键盘的starting框架矩形。框架矩形反映了设备的当前方向。

<强>结论

因此,如果你使用UIKeyboardFrameBeginUserInfoKey,你的键盘高度可能会达到0。导致系统思想UITextView未被涵盖。

答案 3 :(得分:1)

找到正确的键盘高度并将其指定给textView的底部约束或缩小textView的y位置。 喜欢:

<强>步骤1: 在viewController中创建一个属性keyboardHeight。

var keyboardHeight: CGFloat = 0.0

第2步:制作textView底部约束的@IBOutlet

@IBOutlet weak var textViewBottomConstraint: NSLayoutConstraint!

<强>步骤-3:

fileprivate func addKeyboardNotification() {
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

fileprivate func removeKeyboardNotification() {
    IQKeyboardManager.shared().isEnabled = true
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

复制&amp;将这些函数粘贴到视图控制器,然后调用self.addKeyboardNotification()中的viewDidLoad()和viewController

<强>步骤-4:

deinit {
    self.removeKeyboardNotification()
}

还将此代码添加到viewController。

<强>步骤5:

    func keyboardWillShow(_ notification: Notification) {
    if let keboardFrame = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue, self.keyboardHeight <= 0.0 {
        self.keyboardHeight = keboardFrame.height + 45.0 //(Add 45 if your keyboard have toolBar if not then remove it)
    }

    UIView.animate(withDuration: 0.3, animations: {
        self.textViewBottomConstraint.constant = self.keyboardHeight
    }, completion: { (success) in
    })
}

func keyboardWillHide(_ notification: Notification) {
    UIView.animate(withDuration: 0.3, animations: {
        self.textViewBottomConstraint.constant = 0.0
    }, completion: { (success) in
    })
}

这是用键盘管理textView的。 如果您不想使用textViewBottomConstraint,则可以使用textView的y位置。

答案 4 :(得分:1)

您只需使用TPKAScrollViewController.h&amp;使用桥接标头的TPKAScrollViewController.m个文件。

将这些objective-C文件拖到swift项目中时,它会自动询问Create Bridging。创建桥接标头并将#import "TPKAScrollViewController.h"导入YourApp-Bridging-Header.h文件。

enter image description here

之后,只需在XIB中选择您的scrollView并将其类更改为TPKeyboardAvoidingScrollView,如下所示。

enter image description here