我正在创建一个简单的信使聊天窗口,我正在使用UICollectionView
作为我的泡泡消息。
现在我想设置键盘以正确显示和隐藏。
我使用了NSNotifications
并为keyboardWillShow:
和keyboardWillHide:
事件创建了函数。另外,我为keyboardDismissMode
设置了CollectionView
到Interactive。
所以现在,当我向上滚动,我的键盘隐藏(由交互式解雇模式引起)时,我还得到keyboardWillHid
e事件,这会重置我的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
}
}
答案 0 :(得分:2)
当您以交互方式关闭键盘而不是因为UIEdgeInsets被重置为零时,您的collectionView会滚动到底部,而是因为在此配置中,当您以交互方式关闭键盘时,将再次调用keyboardWillShow方法。大概是因为inputAccessoryView。要验证这一点,请将println放入keyboardWillShow方法并再次尝试。我想说这是一个评论而不是一个答案,但我只有47个代表,需要50个评论。但我认为这些信息对您有用。