gpt4 book ai didi

ios - 根据键盘是否可见更改 TextView 的框架

转载 作者:可可西里 更新时间:2023-11-01 01:56:42 25 4
gpt4 key购买 nike

我正在使用观察器来确定键盘是否被隐藏。键盘应该在 View 加载后立即自动显示,这应该触发调整 View 的观察者。当 View 加载时,键盘出现,但仍然有部分 TextView 隐藏在键盘后面,一旦您隐藏键盘并再次显示它,它将正确调整 TextView 的大小。

在 viewDidLoad 中我添加了观察者

let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: UIResponder.keyboardDidHideNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: UIResponder.keyboardDidHideNotification, object: nil)

我的textview成为viewDidAppear中的第一响应者

override func viewDidAppear(_ animated: Bool) {

noteTextView.becomeFirstResponder()

}

最终 View 得到调整

@objc func adjustForKeyboard(notification: Notification) {
let userInfo = notification.userInfo!

let keyboardScreenEndFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let keyboardViewEndFrame = view.convert(keyboardScreenEndFrame, from: noteTextView.window)

if notification.name == UIResponder.keyboardWillHideNotification {
noteTextView.contentInset = UIEdgeInsets.zero
} else {
noteTextView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardViewEndFrame.height, right: 0)
}

noteTextView.scrollIndicatorInsets = noteTextView.contentInset

let selectedRange = noteTextView.selectedRange
noteTextView.scrollRangeToVisible(selectedRange)
}

我该如何解决这个问题,以便它在第一时间正确显示?使用最新版本的 xcode。

隐藏键盘之前

Part of textview is behind keyboard

隐藏键盘后可以看到textview隐藏在了它的后面

Textview in full size after hiding keyboard

再次显示键盘后,textview 的大小被调整。

Keyboard is shown 2nd time

最佳答案

你复制了keyboardDidHideNotification

notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: UIResponder.keyboardDidHideNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: UIResponder.keyboardDidHideNotification, object: nil)

你还需要keyboardWillShowNotification

notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: UIResponder.keyboardDidHideNotification, object: nil) 
notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: UIResponder.keyboardWillShowNotification, object: nil)

关于ios - 根据键盘是否可见更改 TextView 的框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52674655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com