我正在开发一个用 Swift 编写的 macOS 消息客户端。我使用 NSScrollView 和 NSCollectionView 作为文档 View 来呈现消息。目前,我已经实现了无限滚动,但现在的问题是 collectionView 从顶部开始加载单元格并向下加载 - 这是 NSCollectionView 的默认行为。相反,我需要它从底部开始并向上工作 - 就像典型的消息应用程序显示消息的方式。
我尝试过的解决方案:
- 一旦 View 加载或用户选择不同的对话,就会滚动到 collectionView 的底部。这个解决方案明显很糟糕,并且真正搞乱了无限滚动。
- 覆盖scrollView、scrollView的contentView和collectionView中的isFlipped变量。这样做对任何 View 的可见影响为零。
- 将整个scrollView、collectionView、contentView 或collectionView 单元格旋转pi 弧度。作为一种绝望的措施,我尝试旋转整个 ScrollView ,但无法做到这一点,也无法旋转任何 Collection View 项目。我做了一些类似于
wantsLayer = true 的事情 .setAffineTransform(CGAffineTransform(rotationAngle: .pi)) 更新层() setNeedsDisplay(frameRect)
。这同样没有明显的影响。
让 NSCollectionView 从下到上移动的最佳方法是什么?顺便说一句,我没有使用 Storyboard 。
最佳答案
嗨@will,我不确定这段代码是否对您有帮助,因为我已将它用于 iPhone 聊天应用程序,并且它对我有用。就我而言,我只是将 collectionView 放入 View Controller 中。
//MARK:- View Controller life cycle method
override func viewDidLoad() {
chatCollectionView.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if(keyPath == "contentSize"){
if let newvalue = change?[.newKey] {
let contentHeight: CGFloat = chatCollectionView.contentSize.height
let collectionHeight = chatCollectionView.frame.size.height
if contentHeight < collectionHeight {
var insets: UIEdgeInsets = chatCollectionView.contentInset
insets.top = collectionHeight - contentHeight
chatCollectionView.contentInset = insets
} else {
chatCollectionView.contentInset = .zero
}
}
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
chatCollectionView.removeObserver(self, forKeyPath: "contentSize")
}
关于Swift NSCollectionView 从下到上的流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54431199/