具有垂直和水平功能的NSCollectionView

时间:2019-01-07 08:48:12

标签: swift macos nscollectionview

我正在使用NSCollectionView进行列表。它可能包含许多列和行。看来我只能垂直或水平滚动视图。 Sample

我了解到的痛点是,CollectionView内容大小的宽度会自动设置为scrollview中documentview的宽度。但是对于其他类型的视图,例如NSImageView,其大小将不会调整。

sample

这是代码

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

}

0 个答案:

没有答案