gpt4 book ai didi

ios - 添加项目时使 uitextfield 滚动到底部

转载 作者:行者123 更新时间:2023-11-28 08:04:31 27 4
gpt4 key购买 nike

我有一个 collectionViewController 和一个 inputContainerAccessoryView,里面有一个 uitextfield。每次我在键盘上按回车,一个项目(一行)被添加到collectionview,我想让collectionview自动滚动到它的底部;我还希望当键盘出现时,它也会滚动到 Collection View 的底部。我试过一个代码,但没有按我想要的方式滚动:

viewDidLoad

collectionView?.keyboardDismissMode = .interactive

NotificationCenter.default.addObserver(
self,
selector: #selector(HomeViewController.keyboardWillShow(event:)),
name: NSNotification.Name.UIKeyboardWillShow,
object: nil
)

文本字段应该返回

handleKeyboardDidShow()

方法

func keyboardWillShow(event: Notification) {
//let keyboardqlq = inputTextField.frame.height
guard let keyboardFrame = (event.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
guard let colelctionview = self.collectionView else { return }

colelctionview.contentInset.bottom = keyboardFrame.height - 200
colelctionview.scrollIndicatorInsets.bottom = keyboardFrame.height - 200

// do NOT scroll messages if the keyboard is the `accessoryView`
if keyboardFrame.height != inputContainerView.frame.height {
handleKeyboardDidShow()
}
}


func handleKeyboardDidShow() {

if messages.count > 0 {
let indexPath = IndexPath(item: messages.count - 1, section: 0)
collectionView?.scrollToItem(at: indexPath, at: .bottom, animated: true)
}
}

最佳答案

也许它效率不高,但它解决了问题。确保文本字段委托(delegate)是自己的。

 var needToScroll :Bool = true

func textFieldDidBeginEditing(_ textField: UITextField) {
needToScroll = true
}
func handleKeyboardWillHide(notification:Notification) {
let keyboardDuration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? Double

UIView.animate(withDuration: keyboardDuration!) {
self.view.layoutIfNeeded()
self.chatLogCollectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 30, right: 0)

self.needToScroll = false
}

}
func handleKeyboardWillShow(notification:Notification) {

let keyboardFrame = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect
let keyboardDuration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? Double

UIView.animate(withDuration: keyboardDuration!) {
self.view.layoutIfNeeded()
self.chatLogCollectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: (keyboardFrame?.height)!, right: 0)


if self.needToScroll {
if self.chatLogCollectionView.messages.count > 0 {

self.chatLogCollectionView.scrollToItem(at: NSIndexPath(item: self.chatLogCollectionView.messages.count - 1, section: 0) as IndexPath, at: .bottom, animated: false)
}
}

}

}

关于ios - 添加项目时使 uitextfield 滚动到底部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45536932/

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