使用unobjanager的@objc属性值类型枚举-快速方法?

时间:2019-01-15 15:10:40

标签: swift cocoa enums nsundomanager

如何实现swift枚举属性以正确处理撤消?

当前我使用(undoManager?.prepare(withInvocationTarget: self) as AnyObject).setValue(_scaling.rawValue, forKey: "scaling"),但是它在值0上失败。setnilvalueforKey没有被调用,但是setValue(_ value: Any?, forKey key: String)被调用了,但是有时会崩溃。

如何使其更加迅速?

@objc
enum ImageScaling : Int {
    case FitInSquare
    case None
}

private var _scaling : ImageScaling = .FitInSquare
@objc dynamic var scaling : ImageScaling {
    get {
        return _scaling
    }
    set(newValue) {
        guard (_scaling != newValue) else { return }
        //doesn't work
        //undoManager?.registerUndo(withTarget: self, selector: #selector(setter: Picture.scaling), object: _scaling)
        //setnilvalueforKey if 0, doesn't work for 0 in swift
        (undoManager?.prepare(withInvocationTarget: self) as AnyObject).setValue(_scaling.rawValue, forKey: "scaling")
        undoManager?.setActionName("Change Scaling")
        document?.beginChanges()
        _scaling = newValue
        document?.endChanges()
    }
}


override func setValue(_ value: Any?, forKey key: String) {
    if (key == "scaling") {
        if (value as? Int == 0) {
            scaling = .FitInSquare
        } else {
            super.setValue(value, forKey: key)
        }
    } else {
        super.setValue(value, forKey: key)
    }
}

//doesn't get called
override func setNilValueForKey(_ key: String) {
    if (key == "scaling") {
        scaling = .FitInSquare
    } else {
        super.setNilValueForKey(key)
    }
}

0 个答案:

没有答案