gpt4 book ai didi

ios - 存在键盘时快速向上移动 ScrollView

转载 作者:行者123 更新时间:2023-11-28 11:06:49 24 4
gpt4 key购买 nike

我正在开发一个 iOS 应用程序,目前我的所有元素都在 ScrollView 中,当键盘出现时,我将 View 向上移动 250 磅。这解决了我的问题,但每个设备的键盘大小始终不同。

如何检测我的文本字段离屏幕底部有多远以及键盘有多高?

最佳答案

您应该观察显示和隐藏键盘的通知。之后,您可以获得准确的键盘大小,并移动或更改 ScrollView 的内容插图。这是示例代码:

extension UIViewController {
func registerForKeyboardDidShowNotification(scrollView: UIScrollView, usingBlock block: (NSNotification -> Void)? = nil) {
NSNotificationCenter.defaultCenter().addObserverForName(UIKeyboardDidShowNotification, object: nil, queue: nil, usingBlock: { (notification) -> Void in
let userInfo = notification.userInfo!
let keyboardSize = userInfo[UIKeyboardFrameBeginUserInfoKey]?.CGRectValue.size
let contentInsets = UIEdgeInsetsMake(scrollView.contentInset.top, scrollView.contentInset.left, keyboardSize!.height, scrollView.contentInset.right)

scrollView.scrollEnabled = true
scrollView.setContentInsetAndScrollIndicatorInsets(contentInsets)
block?(notification)
})
}

func registerForKeyboardWillHideNotification(scrollView: UIScrollView, usingBlock block: (NSNotification -> Void)? = nil) {
NSNotificationCenter.defaultCenter().addObserverForName(UIKeyboardWillHideNotification, object: nil, queue: nil, usingBlock: { (notification) -> Void in
let contentInsets = UIEdgeInsetsMake(scrollView.contentInset.top, scrollView.contentInset.left, 0, scrollView.contentInset.right)
scrollView.setContentInsetAndScrollIndicatorInsets(contentInsets)
scrollView.scrollEnabled = false
block?(notification)
})
}
}

extension UIScrollView {
func setContentInsetAndScrollIndicatorInsets(edgeInsets: UIEdgeInsets) {
self.contentInset = edgeInsets
self.scrollIndicatorInsets = edgeInsets
}
}

在您要移动 ScrollView 的 UIViewController 中,只需在 viewDidLoad() 函数下添加下一行

override func viewDidLoad() {
super.viewDidLoad()

registerForKeyboardDidShowNotification(scrollView)
registerForKeyboardWillHideNotification(scrollView)
}

关于ios - 存在键盘时快速向上移动 ScrollView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37090765/

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