Is there a way to set up a NSCollectionView programmatically in Swift?

后端 未结 3 2121
猫巷女王i
猫巷女王i 2020-12-15 12:09

I\'m coming from the iOS development and I am wondering if there is a way to set up a NSCollectionView programmatically like a UICollectionView in

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-15 12:30

    You need to embed NSCollectionView within NSScrollView. Code below is in Swift 4

    Setup NSCollectionView

    let layout = NSCollectionViewFlowLayout()
    layout.minimumLineSpacing = 4
    
    collectionView = NSCollectionView()
    collectionView.dataSource = self
    collectionView.delegate = self
    collectionView.collectionViewLayout = layout
    collectionView.allowsMultipleSelection = false
    collectionView.backgroundColors = [.clear]
    collectionView.isSelectable = true
    collectionView.register(
      Cell.self,
      forItemWithIdentifier: NSUserInterfaceItemIdentifier(rawValue: "Cell")
    )
    

    Setup NSScrollView

    scrollView = NSScrollView()
    scrollView.documentView = collectionView
    view.addSubview(scrollView)
    

    Here's a simple NSCollectionViewItem

    class Cell: NSCollectionViewItem {
      let label = NSTextField()
      let imageView = NSImageView()
    
      override func loadView() {
        self.view = NSView()
        self.view.wantsLayer = true
      }
    }
    

提交回复
热议问题