我有 NSCollectionView 里面有项目。我有 NSCollectionViewItem 的 xib,绑定到表示的Object.image
我的问题如下。有时我的项目应该显示“空图像”,直到我通过我的控件为此选择图像。当我选择图像时 - 我将它存储在代表对象的 .image 属性中,绑定会更新视图,一切都很酷。
我可以在集合内旋转我的 imageview。一切都很好,除了上面的情况,当我为空的图像选择图像时,视图正在更新,绑定显示正确的图像,但是如果我在那之后尝试旋转视图 - 它不能正常工作。它仅在添加它的位置旋转显示,但如果我旋转到不同的角度 - 它就会消失。通过 KVO 正在观察旋转。
这是我拥有的代码:
class CollectionViewItem: NSCollectionViewItem {
//Init
override init?(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.addObserver(self, forKeyPath: "modelRepresentation.Rotation", options: [.new, .old], context: nil)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
//Properties
@objc dynamic var modelRepresentation : Artwork?
override var highlightState: NSCollectionViewItemHighlightState {
get {
return super.highlightState
}
set(newHighlightState) {
super.highlightState = newHighlightState
// Relay the newHighlightState to our AAPLSlideCarrierView.
guard let carrierView = self.view as? LibraryViewItemCarrierView else {return}
carrierView.highlightState = newHighlightState
}
}
override var isSelected: Bool {
get {
return super.isSelected
}
set {
super.isSelected = newValue
guard let carrierView = self.view as? LibraryViewItemCarrierView else {return}
carrierView.selected = newValue
}
}
override var representedObject: Any? {
get {
return super.representedObject as AnyObject?
}
set(newRepresentedObject) {
super.representedObject = newRepresentedObject
if let model = newRepresentedObject as? Artwork {
modelRepresentation = model
imageView?.rotate(byDegrees: CGFloat((model.Rotation)))
}
}
}
// 2
override func viewDidLoad() {
super.viewDidLoad()
view.wantsLayer = true
view.layer?.backgroundColor = NSColor(red: 15/255, green: 34/255, blue: 42/255, alpha: 1).cgColor
view.layer?.borderWidth = 0.0
view.layer?.borderColor = NSColor.lightGray.cgColor
}
override func prepareForReuse() {
super.prepareForReuse()
imageView?.boundsRotation = 0
}
func setHighlight(_ selected: Bool) {
view.layer?.borderWidth = selected ? 3.0 : 0.0
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let kind = change![NSKeyValueChangeKey.kindKey]! as! UInt
if(keyPath == "modelRepresentation.Rotation")
{
if kind == NSKeyValueChange.setting.rawValue {
guard let newVal = change![.newKey]! as? Int,
let oldVal = change![.oldKey]! as? Int else {return}
let delta = newVal - oldVal
imageView?.rotate(byDegrees: CGFloat(delta))
}
}
}
}