【问题标题】:How do we make keyboard appear below textView in swift?我们如何让键盘快速出现在 textView 下方?
【发布时间】:2018-04-19 10:50:48
【问题描述】:

我已经使用

完成了出现在文本字段下方的键盘

在 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 相同的代码,但没有积极效果

【问题讨论】:

  • 您遇到了什么问题?试着检查你能得到键盘的高度吗?如果没有,你可以使用UIKeyboardFrameEndUserInfoKey
  • 如果我对 textview 执行相同的代码,键盘会覆盖 textview。
  • 我确实得到了身高

标签: swift swift3 swift2


【解决方案1】:

一种简单且无代码的在线解决方案是在您的应用中使用以下 pod。

IQKeyboardManger

稍后您只需将其导入 App Delegate 并在 didfinishLaunching 方法中添加这两行代码:

  IQKeyboardManager.sharedManager().enable = true

您的问题将在整个应用程序中得到解决。

对于 Swift 5:

IQKeyboardManager.shared.enable = true

【讨论】:

    【解决方案2】:

    我曾经经历过这样的情况。首先,我在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
        }
    

    【讨论】:

      【解决方案3】:

      您可以通过使用桥接头来简单地使用 TPKAScrollViewController.hTPKAScrollViewController.m 文件。

      在将这些 Objective-C 文件拖到您的 swift 项目时,它会自动要求创建桥接。创建桥接头并将 #import "TPKAScrollViewController.h" 导入 YourApp-Bridging-Header.h 文件。

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

      【讨论】:

      • 嗨 @Jeesson_7 试试这个,它在 textfield 和 textView 上 100% 工作。
      【解决方案4】:

      Salman Ghumsani 是对的。

      请将UIKeyboardFrameBeginUserInfoKey 更改为UIKeyboardFrameEndUserInfoKey

      Apple Debeloper Document: Keyboard Notification User Info Keys

      UIKeyboardFrameEndUserInfoKey

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

      UIKeyboardFrameBeginUserInfoKey

      一键 NSValue 包含一个对象 CG矩形 以屏幕坐标标识键盘的starting 框架矩形。框架矩形反映了设备的当前方向。

      结论

      因此,如果您使用UIKeyboardFrameBeginUserInfoKey,您可能会将键盘高度设置为0。导致系统认为UITextView未被覆盖。

      【讨论】:

      • 我试过了。它不起作用。此外,当它的文本字段具有相同的代码时,我得到了高度
      • 1. UIKeyboardFrameBeginUserInfoKey 适用于 textfield 但不适用于 textview
      • 2.我试过了,它奏效了。你忘了把activeField改成activeTextView吗?
      【解决方案5】:

      找到正确的键盘高度并将其分配给textView的底部约束或减少textView的y位置。 喜欢:

      第 1 步: 在 viewController 中创建一个属性 keyboardHeight。

      var keyboardHeight: CGFloat = 0.0

      第二步:@IBOutlet设置为textView的底部约束。

      @IBOutlet weak var textViewBottomConstraint: NSLayoutConstraint!

      第三步:

      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)
      }
      

      将这些函数复制并粘贴到您的视图控制器,并在 viewDidLoad() 和您的视图控制器中调用 self.addKeyboardNotification()

      第四步:

      deinit {
          self.removeKeyboardNotification()
      }
      

      还将此代码添加到您的 viewController。

      第五步:

          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 位置。

      【讨论】:

        猜你喜欢
        • 2020-07-09
        • 2016-05-07
        • 2017-01-08
        • 2021-12-05
        • 1970-01-01
        • 2020-03-02
        • 2015-01-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多