SWIFT 键盘与内容重叠

标签 swift notifications uiscrollview

在我的 loginViewController 上有一个 textField 和一个用于搜索的 button。我想确保在 textField 中输入文本时,我的界面不会被键盘重叠,而是滚动到该键盘的大小并且可以访问所有元素。为此,我写了这段代码:

override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.addObserver(self, selector: #selector(kbDidShow), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(kbDidHide), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
    }

    @objc func kbDidShow(notification: Notification) {
        guard let userInfo = notification.userInfo else { return }
        let kdFrameSize = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        (self.view as! UIScrollView).contentSize = CGSize(width: self.view.bounds.size.width, height: self.view.bounds.size.height + kdFrameSize.height)
        (self.view as! UIScrollView).scrollIndicatorInsets = UIEdgeInsets(top: 0, left: 0, bottom: kdFrameSize.height, right: 0)
    }

    @objc func kbDidHide() {
        (self.view as! UIScrollView).contentSize = CGSize(width: self.view.bounds.size.width, height: self.view.bounds.size.height)
    }

当我运行应用程序时,我看到了滚动条的侧 View ,但界面本身并没有滚动。 可能是什么问题?

最佳答案

尝试使用 IQKeyboardManager 这会自动完成你的工作 链接 - https://github.com/hackiftekhar/IQKeyboardManager

你只需要在 AppDelegate 中添加这一行 在每个 View 中,所有文本字段都将自动调整。

IQKeyboardManager.sharedManager().enable = true

关于SWIFT 键盘与内容重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51152515/

相关文章:

Swift NSBlockOperation() 泄漏 : cannot make NSBlockOperation() weak

ios - 从通知对象传递数组会导致 iOS 10 中的应用程序崩溃

ios - 应用程序首选项 : root=NOTIFICATIONS_ID Not working on iOS 11 Swift 4

iphone - 通过 Facebook 登录后应用程序介绍如何下次跳过介绍?

swift - 使用闭包/解析器初始化 promise 时,我们可以直接抛出吗?

Swift - 带条件的 GCD 定时器

android - Android 中传入短信的状态栏通知?

ios5 - 在 iOS 5 中子类化 UIScrollView 时无法拖动对象,有帮助吗?

ios - 使用三个 View 的无限循环对 UIScrollView 进行分页

objective-c - 将 Swift 单元测试添加到混合语言 Xcode 项目