【发布时间】:2015-08-22 04:04:40
【问题描述】:
我正在创建一个简单的信使聊天窗口,并且我正在使用UICollectionView 来发送我的气泡消息。
现在我想设置键盘以正确显示和隐藏。
我使用了NSNotifications 并为keyboardWillShow: 和keyboardWillHide: 事件创建了函数。我还为我的CollectionView 设置了keyboardDismissMode 到 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
}
}
【问题讨论】:
标签: ios swift uiscrollview keyboard uicollectionview