我正在使用 NSCollectionView 和 NSCollectionViewItems。
我遇到了以下问题:如果我旋转其中一项的 NSImageView,然后调用 reloadData,更新后的视图会被搞砸。旋转会跳到下一个项目,角度会不同等等。
图片和代码如下:
轮换代码:
let collectionViewItem = collectionView.item(at: ip) as? LibraryViewItem
collectionViewItem?.imageView?.rotate(byDegrees: CGFloat(degree))
collectionViewItem?.model?.Rotation! += degree
collectionViewItem.reloadData()
模型:
class LibraryViewItem: NSCollectionViewItem {
// 1
var model: ImageModel? {
didSet {
guard isViewLoaded else {
print("asd")
return }
if let imageFile = model {
imageView?.image = imageFile.thumbnail
textField?.stringValue = imageFile.fileName
} else {
imageView?.image = nil
textField?.stringValue = ""
}
}
}
// 2
override func viewDidLoad() {
super.viewDidLoad()
view.wantsLayer = true
view.layer?.backgroundColor = NSColor.white.cgColor
// 1
view.layer?.borderWidth = 0.0
// 2
view.layer?.borderColor = NSColor.lightGray.cgColor
}
func setHighlight(_ selected: Bool) {
view.layer?.borderWidth = selected ? 5.0 : 0.0
}
}
委托方式:
func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
let item = collectionView.makeItem(withIdentifier: "LibraryViewItem", for: indexPath)
guard let collectionViewItem = item as? LibraryViewItem else {return item}
let libraryModel = itemsToShow[indexPath.item]
collectionViewItem.model = libraryModel
if let selectedIndexPath = collectionView.selectionIndexPaths.first, selectedIndexPath == indexPath {
collectionViewItem.setHighlight(true)
} else {
collectionViewItem.setHighlight(false)
}
return item
}