【问题标题】:how to offset text view equals height of the keyboard in swift 3?如何在swift 3中偏移文本视图等于键盘的高度?
【发布时间】:2018-01-13 01:29:02
【问题描述】:

我的项目中有一个文本视图,我希望当用户点击文本字段时它向上移动等于键盘的高度我使用此代码获取键盘的高度,它给了我键盘的大小

static var sizeForOffsetKeyboard = CGFloat()

    var heightKeyboard : CGFloat?
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardShown(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
}

func keyboardShown(notification: NSNotification) {
    if let infoKey  = notification.userInfo?[UIKeyboardFrameEndUserInfoKey],
        let rawFrame = (infoKey as AnyObject).cgRectValue {
        let keyboardFrame = view.convert(rawFrame, from: nil)
        self.heightKeyboard = keyboardFrame.size.height

        levelChatViewController.sizeForOffsetKeyboard = heightKeyboard!

        print(levelChatViewController.sizeForOffsetKeyboard)
        // Now is stored in your heightKeyboard variable
    }
}

但我没有得到结果,textview不会随着键盘的高度向上移动

这里是偏移文本视图的代码

func textViewDidBeginEditing(_ textView: UITextView) {


   animateViewMoving(up: true, moveValue: levelChatViewController.sizeForOffsetKeyboard)
}

【问题讨论】:

  • 您可以使用 UITableViewController 进行自动滚动。在这里查看我的答案stackoverflow.com/questions/45233089/…
  • 我使用了stackoverflow.com/questions/26070242/… 并且没问题但是当文本字段正在编辑并且用户更改键盘时,文本字段不会随着新键盘移动
  • 当键盘基于当前选择的文本文件时,您必须继续添加高度。你可以使用 UITableViewController,零代码就可以实现你想要的。
  • 您可以在您共享的链接中查看 Celil、Fedya 和 Rohit 的答案。这些答案对您的情况可能会有所帮助。
  • 我没有使用 UITableViewController 并且由于很多代码我无法更改它,您可以给我另一种方式吗?

标签: ios swift3 keyboard uitextfield


【解决方案1】:

最简单的方法是使用 IQKeyboardManagerSwift

添加吊舱

      pod 'IQKeyboardManagerSwift'

在您的 AppDelegate 中

     import IQKeyboardManagerSwift

在 didFinishLaunchingWithOptions 里面

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    IQKeyboardManager.sharedManager().enable = true

     }

这将管理您项目的所有文本文件,您无需在其他任何地方编写任何内容

只要你喜欢就尝试一下

了解更多https://github.com/hackiftekhar/IQKeyboardManager

【讨论】:

  • 我不想使用 pod 文件,因为我的项目非常庞大
  • 745 KB 大小
  • 我已阅读,感谢您的帮助,但我需要一些简单的东西,所以我决定获取尺寸手册,感谢您的帮助
猜你喜欢
  • 2020-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-07
  • 2017-03-15
相关资源
最近更新 更多