swift - 可可 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
}
}
解决方案
推荐阅读
- laravel - 在 Laravel 中更改查询字符串的值
- after-effects - After Effects - 合成选项卡中的双视图
- php - PHP Laravel REST api 双反关系
- python-3.x - TensorFlow 2.0 - 学习率调度器
- typescript - 在 Typescript 中使用交集类型扩展函数参数类型
- kotlin - 使用 Kotlin Exposed 创建数据库后连接到数据库
- jquery - How to modify close button in submenu of jQuery mobile for initial opening
- java - 如果我按 Enter 或关闭键盘,EditText 会更改大小
- sip - Linphone opus 编解码器采样率
- components - 在 App 组件旁边动态呈现 Blazor 组件