0

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.

sample

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)
    }

}
Willeke
  • 14,578
  • 4
  • 19
  • 47
anergy7
  • 1
  • 5
  • How do you want to scroll? Is using `NSCollectionView` in legacy mode a must? If not, which layout do you want to use? Do you want to use sections? – Willeke Jan 07 '19 at 09:34
  • not a must. Can you access to the sample picture? I want to use sections. – anergy7 Jan 07 '19 at 10:04
  • the requirement is quite simple. A collectionview with many rows and columns, which cannot be shown in a page. I want to enable scrolling both vertically and horizontally. – anergy7 Jan 07 '19 at 10:06
  • If you want to create a legacy collection view in code, see [Is there a way to set up a NSCollectionView programmatically in Swift?](https://stackoverflow.com/questions/30061679/is-there-a-way-to-set-up-a-nscollectionview-programmatically-in-swift/30065714) and the linked question with explanation. – Willeke Jan 07 '19 at 10:49
  • it‘s irrelevant to the question – anergy7 Jan 07 '19 at 11:22

0 Answers0