I am making a list by using NSCollectionView. It may contain many columns and rows. It seems that I can only scroll the view either vertically or horizontally. Sample
I understand the painpoint is that, the width of CollectionView content size is automatically set to the width of documentview in scrollview. But for other kinds of view, such as NSImageView, the size won't be adjusted.
here are the codes
import Cocoa
class ViewController: NSViewController {
override var representedObject: Any? {
didSet {
}
}
var titles = [String]()
var collectionView: NSCollectionView?
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
func setup(){
self.titles = ["Banana", "Apple", "Strawberry", "Cherry", "Pear", "Pineapple", "Grape", "Melon"]
collectionView = NSCollectionView()
collectionView!.itemPrototype = CollectionViewItem()
collectionView!.content = self.titles
collectionView?.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
(collectionView?.widthAnchor.constraint(equalToConstant: 2000))!,
(collectionView?.heightAnchor.constraint(equalToConstant: 2000))!
])
collectionView?.setFrameSize(NSSize(width: 2000, height: 2000))
var index = 0
for title in titles {
var item = self.collectionView!.item(at: index) as! CollectionViewItem
item.getView().button?.title = self.titles[index]
index = index + 1
}
var scrollView = NSScrollView(frame: NSRect(x: 0, y: 0, width: 400 , height: 200))
let clipView = scrollView.contentView
scrollView.backgroundColor = NSColor.red
scrollView.documentView = collectionView
self.view.addSubview(scrollView)
}
}