键盘隐藏我的文本字段,我的解决方案代码没有工作

时间:2018-03-28 07:01:29

标签: ios swift uitextfield uikeyboard cgaffinetransform

你好关于键盘隐藏文本字段问题有很多问题

我在简单的和复杂的一点之间看到了许多解决方案

我试图通过origin.y

提升我的观点 键盘显示时

self.view.frame.origin.y = -150

键盘隐藏

self.view.frame.origin.y = 0

有时它可以工作但不是现在

当键盘显示时,视图向上移动但是当它像这样下降时它有黑色区域

键盘显示

enter image description here

键盘向下

enter image description here

当然,它出现在我的真实设备中的问题是什么?

所以我像这样使用CGAffineTransform ,它有效!

@objc func keyboardWillHide(_ sender: Notification){
    self.view.transform = .identity
}

@objc func keyboardWillShow(_ sender: Notification){
    guard let userInfo = sender.userInfo as? [String:Any] else {return}
    guard let keyboardFrame = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue else {return}
    self.view.transform = CGAffineTransform(translationX: 0, y: -keyboardFrame.cgRectValue.height + 60)
}
好吗?或有潜在错误?

4 个答案:

答案 0 :(得分:0)

这不会隐藏您的键盘。当键盘出现时,您可以滚动文本字段,只需 -

  

在故事板中制作UIScrollView

并在ViewController -

中写下此代码
import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var scrollView: UIScrollView!

    //MARK: - // left it as it is, don't make it's connection with storyboard
    @IBOutlet weak var activeTextField: UITextField? 

    override func viewWillAppear(_ animated: Bool) {
        self.setNotificationKeyboard()
    }

    // Notification when keyboard show
    func setNotificationKeyboard ()  {
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: .UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: .UIKeyboardWillHide, object: nil)
    }

    //MARK: - get current text field
    func textFieldDidBeginEditing(_ textField: UITextField) {
        activeTextField = textField;
    }
    func textFieldDidEndEditing(_ textField: UITextField) {
        activeTextField = nil
    }
    //MARK: - when show keyboard increase height of scroll view
    func keyboardWasShown(notification: NSNotification)
    {
        var info = notification.userInfo!
        let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
        let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height+10, 0.0)
        self.scrollView.contentInset = contentInsets
        self.scrollView.scrollIndicatorInsets = contentInsets
        var aRect : CGRect = self.view.frame
        aRect.size.height -= keyboardSize!.height
        if let activeField = self.activeTextField
        {
            if (!aRect.contains(activeField.frame.origin))
            {
                self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
            }
        }
    }
    //MARK: - when keyboard hide reduce height of scroll view
    func keyboardWillBeHidden(notification: NSNotification){
        let contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0,0.0, 0.0)
        self.scrollView.contentInset = contentInsets
        self.scrollView.scrollIndicatorInsets = contentInsets
        self.view.endEditing(true)
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if let nextField = textField.superview?.superview?.viewWithTag(textField.tag + 1) as? UITextField {
            nextField.becomeFirstResponder()
        } else {
            textField.resignFirstResponder()
        }

        return false
    }

}

答案 1 :(得分:0)

操作UIViewController的基本视图并不是一个好主意。你可以而且很可能遇到一些奇怪的问题。

我建议您将需要移动的所有内容嵌入到自己的UIView中:选择所有子视图,编辑器 - >嵌入 - >图即可。添加所有必需的约束并为底部约束创建IBOutlet - inputViewBottomConstraint

然后在你的视图控制器中添加:

fileprivate func subscribeToNotifications() {
    NotificationCenter.default.addObserver(forName: .UIKeyboardWillShow, object: nil, queue: nil) { [weak self] notification in
        self?.updateInputViewConstraints(withUserInfo: notification.userInfo, isAppearing: true)
    }
    NotificationCenter.default.addObserver(forName: .UIKeyboardWillHide, object: nil, queue: nil) { [weak self] notification in
        self?.updateInputViewConstraints(withUserInfo: notification.userInfo, isAppearing: false)
    }
}

fileprivate func updateInputViewConstraints(withUserInfo userInfo: [AnyHashable: Any]?, isAppearing: Bool) {
    let keyboardFrame = userInfo?[UIKeyboardFrameEndUserInfoKey] as! CGRect
    let animationDuration = userInfo?[UIKeyboardAnimationDurationUserInfoKey] as! Double
    let animationCurve: UIViewAnimationOptions = {
        let curve = userInfo?[UIKeyboardAnimationCurveUserInfoKey] as! UInt
        return UIViewAnimationOptions(rawValue: curve)
    }()
    inputViewBottomConstraint.constant = isAppearing ? keyboardFrame.size.height : 0
    UIView.animate(withDuration: animationDuration, delay: 0, options: animationCurve, animations: {
        self.view.layoutSubviews()
    }, completion: nil)
}

答案 2 :(得分:0)

在iOS应用程序中有一个非常好的库来管理键盘 https://github.com/hackiftekhar/IQKeyboardManager

你应该使用这个库。

答案 3 :(得分:0)

  

由于屏幕的一部分隐藏在键盘后面,所以你   可以使用滚动视图 - 然后用户可以向上滚动   下来访问整个屏幕。

在xib或Storyboard文件中,添加UIScrollView。假设您已经添加了元素,快速执行此操作的方法是 -

  1. 选择要放入屏幕的所有元素 可滚动区域。从XCode的顶部栏中选择编辑器 - >嵌入 - >视图。您可以将此视图重命名为ContentView。
  2. 选择ContentView,现在从XCode的顶部栏中选择编辑器 - >嵌入 - >滚动视图
  3. 对于滚动视图,将顶部,底部,前导和尾随约束设置为0(从Superview / Safe区域中取决于哪个 你正在使用)。
  4. 对于ContentView,设置顶部,底部,左侧和 右边距为0,也设置水平和垂直中心(全部来自scrollView,因为它是superView)。
  5. 现在你可以添加 您在ContentView中的所有视图,以及该内容的contentSize scrollView将相应地自动调整大小。对于您的情况 - 调整您的约束的其余约束 相应的屏幕。比如说,通过给出顶部的垂直间距 内容视图的大多数屏幕元素(类似的过程 最底层的元素)。此步骤与设计任何UI相同 iOS中的屏幕。
  6. 您可以选择执行此步骤以关闭 用户开始滚动时的scrollView。选择滚动视图,点按 在“属性”检查器上,将“键盘”选项设置为“关闭” 拖曳”。
  7.   

    如果您仍想根据键盘是否移动UI元素   出现/显示或隐藏。然后,您可以移动内容View   通过设置scrollView的滚动视图中的位置   setContentOffset财产。

    class SampleViewController: UIViewController {
        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            addKeyboardNotifications()
        }
    
        func addKeyboardNotifications() {             
            NotificationCenter.default.addObserver(self, selector: #selector(SampleViewController.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
            NotificationCenter.default.addObserver(self, selector: #selector(SampleViewController.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
        }
    
        @objc func keyboardWillShow(_ notification: Notification) {
            if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size {
                let keyboardHeight = keyboardSize.height
                // This will move the contentView upwards by the same amount as the height of the keyboard which appears on screen
                scrollView.setContentOffset(CGPoint(x: 0.0, y: keyboardHeight), animated: true)
             }
        }
    
        @objc func keyboardWillHide(_ notification: NSNotification) {
            // This will move the contentView back to it's original position.
            scrollView.setContentOffset(CGPoint(x: 0.0, y: 0.0), animated: true)
        }
    }
    

    希望这有帮助! :)