【Swift Mac开发】通过纯代码的方式创建NSCollectionView (Mac OS X)

  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")
)
复制代码

  NSScrollView

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

  NSCollectionViewItem

复制代码
final class Cell: NSCollectionViewItem {
  let label = Label()
  let myImageView = NSImageView()

  override func loadView() {
    self.view = NSView()
    self.view.wantsLayer = true
  }
}
复制代码

  NSCollectionViewDataSource

复制代码
func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
  return coins.count
}

func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
  let cell = collectionView.makeItem(
    withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "Cell"),
    for: indexPath
  ) as! Cell

  let coin = coins[indexPath.item]

  cell.label.stringValue = coin.name
  cell.coinImageView.image =
    NSImage(named: NSImage.Name(rawValue: "USD"))
    ?? NSImage(named: NSImage.Name(rawValue: "Others"))

  return cell
}
复制代码

  NSCollectionViewDelegateFlowLayout

复制代码
func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
    guard let indexPath = indexPaths.first,
    let cell = collectionView.item(at: indexPath) as? Cell else {
      return
  }
}

func collectionView(_ collectionView: NSCollectionView, didDeselectItemsAt indexPaths: Set<IndexPath>) {
  guard let indexPath = indexPaths.first,
    let cell = collectionView.item(at: indexPath) as? Cell else {
      return
  }
}

func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize {

  return NSSize(
    width: collectionView.frame.size.width,
    height: 40
  )
}
复制代码

 

posted @   Mr·Xu  阅读(667)  评论(0编辑  收藏  举报
编辑推荐:
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
阅读排行:
· 百万级群聊的设计实践
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
历史上的今天:
2019-05-10 微信小程序 + Bmob后端云
2019-05-10 【微信小程序】App.js生命周期
点击右上角即可分享
微信分享提示