UICollectionViewController交互式键盘收起时内容异常跳动问题求助
解决方案:UICollectionView交互式收键盘时内容跳动问题
问题根源
你遇到的跳动问题,本质是自定义inputAccessoryView中错误绑定了safeAreaLayoutGuide.bottomAnchor,导致在带有底部安全区的设备上,交互式收起键盘时输入视图高度随安全区位置动态变化,进而触发UICollectionView的contentInset频繁调整,引发内容跳动。
修复步骤
1. 调整输入视图的约束
修改PlaygroundInputView中textView的底部约束,从绑定安全区底部改为绑定输入视图自身的底部锚点——系统会自动处理inputAccessoryView与底部安全区的间距,无需手动干预:
class PlaygroundInputView: UIView { lazy var textView: UITextView = { var view = UITextView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = .systemGray6 view.isScrollEnabled = false return view }() override init(frame: CGRect) { super.init(frame: frame) self.autoresizingMask = [.flexibleHeight, .flexibleWidth] self.backgroundColor = .systemGray3 addSubview(textView) NSLayoutConstraint.activate([ textView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 12), textView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -12), textView.topAnchor.constraint(equalTo: topAnchor, constant: 8), // 修改:绑定输入视图自身的bottomAnchor textView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -8), ]) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // 修正固有尺寸计算,让系统根据子视图约束自动适配高度 override var intrinsicContentSize: CGSize { UIView.layoutFittingExpandedSize } }
2. 优化CollectionView的内容内边距调整行为
在PlaygroundViewController的viewDidLoad中添加配置,让系统仅在滚动轴方向调整内边距,避免不必要的布局波动:
class PlaygroundViewController: UICollectionViewController { init() { super.init(collectionViewLayout: layout) collectionView.register(PlaygroundCellView.self, forCellWithReuseIdentifier: "cell") collectionView.keyboardDismissMode = .interactive } override func viewDidLoad() { super.viewDidLoad() // 添加内边距调整行为配置 collectionView.contentInsetAdjustmentBehavior = .scrollableAxes becomeFirstResponder() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } lazy var playgroundInputView: UIView = { PlaygroundInputView(frame: .zero) }() override var canBecomeFirstResponder: Bool { true } override var inputAccessoryView: UIView? { playgroundInputView } }
效果说明
修改后,输入视图的高度由内部textView的约束稳定控制,不再随安全区位置变化而波动,系统会自动将inputAccessoryView布局到底部安全区上方,同时UICollectionView的contentInset调整会更平滑,彻底消除交互式收键盘时的内容跳动问题,实现类似Messages的流畅体验。
内容的提问来源于stack exchange,提问作者m_ornj
相关产品推荐
相关产品推荐

