gpt4 book ai didi

ios - swift 为 collectionView 正确关闭键盘

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

我正在创建一个简单的 Messenger 聊天窗口,我正在使用 UICollectionView 作为我的气泡消息。现在我想设置键盘以正确显示和隐藏。我使用了 NSNotifications 并为 keyboardWillShow:keyboardWillHide: 事件创建了函数。我还为我的 CollectionViewkeyboardDismissMode 设置为 Interactive。所以现在,当我向上滚动时,我的键盘隐藏了(由交互式关闭模式引起),我还收到了 keyboardWillHide 事件,它重置了我的 UIEdgeInsets。所以基本上在我向上滚动并且我的键盘被隐藏后,我的 scrollView 立即进入底部。我的目标是让它像在 iMessage.app、WhatsApp 等中一样工作。我将不胜感激任何帮助或建议!

这是我的代码:

class ViewController: UIViewController {

@IBOutlet weak var collectionView: UICollectionView!
var customView: CustomView!

override func viewDidLoad() {
super.viewDidLoad()
customView = CustomView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 40.0))
customView.textView!.delegate = self
collectionView.scrollToBottom(true)
collectionView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.Interactive

NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)

}

override var inputAccessoryView: UIView! {
get {
if customView == nil {
customView = CustomView()
}
return customView
}
}

override func canBecomeFirstResponder() -> Bool {
return true
}

func keyboardWillShow(notification: NSNotification) {
let userInfo = notification.userInfo ?? [:]
let keyboardFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()
let adjustmentHeight = (CGRectGetHeight(keyboardFrame) + CGRectGetHeight(customView.frame) )
let contentInset:UIEdgeInsets
if UIInterfaceOrientationIsPortrait(UIApplication.sharedApplication().statusBarOrientation) {
contentInset = UIEdgeInsetsMake(0, 0, adjustmentHeight, 0)
} else {
contentInset = UIEdgeInsetsMake(0, 0, keyboardFrame.width, 0)
}
collectionView.contentInset = contentInset
collectionView.scrollIndicatorInsets = contentInset
collectionView.scrollToBottom(true)
}

func keyboardWillHide(notification: NSNotification) {
collectionView.contentInset = UIEdgeInsetsZero
collectionView.scrollIndicatorInsets = UIEdgeInsetsZero
}



}

最佳答案

当您以交互方式关闭键盘时,您的 collectionView 滚动到底部不是因为 UIEdgeInsets 被重置为零,而是因为在此配置中,当您以交互方式关闭键盘时,将再次调用 keyboardWillShow 方法。大概是因为inputAccessoryView。要验证这一点,请将 println 放入您的 keyboardWillShow 方法中,然后再试一次。我想说这是评论而不是答案,但我只有 47 个代表,需要 50 个才能发表评论。但我认为这些信息可能对您有用。

关于ios - swift 为 collectionView 正确关闭键盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32152180/

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