首页 > 解决方案 > 可可 CollectionView 按钮操作

问题描述

我制作了一个带有前进和后退按钮的水平 NScollectionView,但是当我单击按钮时,集合中的项目不会移动?

在按钮操作中,我插入了 scrollToVisible 方法,但我认为仍然缺少一些东西。

也许缺少 NSScrollView 扩展?

在此处输入图像描述

@IBAction 按钮连接到左右两个箭头

import Cocoa

class ViewController: NSViewController, NSCollectionViewDelegate, NSCollectionViewDataSource {
    
    var availableUsers = ["User1", "User2", "User3", "User4", "User5", "User6", "User7", "User8", "User9"]
    
    @IBOutlet weak var buttonLeft: NSButton!
    @IBOutlet weak var buttonRight: NSButton!
    
    @IBOutlet weak var scrollView: NSScrollView!
    @IBOutlet weak var collectionView: NSCollectionView!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView.delegate = self
        self.collectionView.dataSource = self
        
        configureCollectionView()
        
    }

    override var representedObject: Any? {
        didSet {
     
        }
    }
    
    
    func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return availableUsers.count
        
    }
    
    
    func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
        
      let item = collectionView.makeItem(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "CollectionViewItem"), for: indexPath)
        
        guard let collectionViewItem = item as? CollectionViewItem else {
            return item
        }
        
        collectionViewItem.labelNew.stringValue = self.availableUsers[indexPath.item]
        
        collectionViewItem.viewNew.layer?.backgroundColor = NSColor.red.cgColor
        
        return item
        
    }
 
    @IBAction func buttonLeft(_ sender: Any) {
        collectionView.scrollToVisible(collectionView.visibleRect.offsetBy(dx: -100, dy: 0))
    }
    
    @IBAction func buttonRight(_ sender: Any) {
        collectionView.scrollToVisible(collectionView.visibleRect.offsetBy(dx: 100, dy: 0))
    }
    
    private func configureCollectionView() {

      let flowLayout = NSCollectionViewFlowLayout()
        
      flowLayout.itemSize = NSSize(width: 160.0, height: 160.0)
      flowLayout.minimumInteritemSpacing = 10.0
      flowLayout.minimumLineSpacing = 10.0
      collectionView.collectionViewLayout = flowLayout

      view.wantsLayer = true
      collectionView.layer?.backgroundColor = NSColor.red.cgColor

    }



}

标签: swiftmacoscocoacollectionview

解决方案


推荐阅读