Ezi*_*met 35 uibutton ios swift
我需要在我的自定义UIButton子类中覆盖UIViews突出显示属性的setter;
目标C.
@property(nonatomic,getter=isHighlighted) BOOL highlighted;
Run Code Online (Sandbox Code Playgroud)
像这样被覆盖了
- (void) setHighlighted:(BOOL)highlighted {
[super setHighlighted:highlighted];
if (highlighted) {
self.backgroundColor = UIColorFromRGB(0x387038);
}
else {
self.backgroundColor = UIColorFromRGB(0x5bb75b);
}
[super setHighlighted:highlighted];
}
Run Code Online (Sandbox Code Playgroud)
迅速
var highlighted: Bool
Run Code Online (Sandbox Code Playgroud)
我试过了:
var highlighted: Bool {
get{ return false }
set {
if highlighted {
self.backgroundColor = UIColor.whiteColor()
//Error "Use unresolved identifier 'self'"
I can't set the background color from value type in here
, can't call self.backgroundColor in this value type ,
can't call super too because this is a value type , doesn't work
}
}
}
Run Code Online (Sandbox Code Playgroud)
如何以及在何处在Swift中实现此方法以获得相同的结果.任何的想法?
Kin*_*ard 37
在斯威夫特上面的解决方案为我,但我不得不省略了布尔=真:
import UIKit
class CustomUIButtonForUIToolbar: UIButton {
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
super.drawRect(rect)
self.layer.borderColor = UIColor.blueColor().CGColor
self.layer.borderWidth = 1.0
self.layer.cornerRadius = 5.0
self.clipsToBounds = true
self.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
self.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Highlighted)
}
override var highlighted: Bool {
didSet {
if (highlighted) {
self.backgroundColor = UIColor.blueColor()
}
else {
self.backgroundColor = UIColor.clearColor()
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这里有一些问题,但这个解决方案可以帮助你......
在您的情况下,因为您并不真正想要突出显示的变量的计算值,而是您想要知道突出显示何时更改,您应该使用willSet或didSet
对于你的情况,didSet.
它看起来像这样
var highlighted:Bool = false {
didSet {
// You can use 'oldValue' to see what it used to be,
// and 'highlighted' will be what it was set to.
if highlighted
{
self.backgroundColor = UIColor.whiteColor()
} else
{
self.backgroundColor = UIColor.blackColor()
}
}
}
Run Code Online (Sandbox Code Playgroud)
请记住,初始值设置为false但是初始化变量不会调用didSet块(我不认为),因此默认使用backgroundColor black ...或其他任何内容初始化此视图.
Swift ibook有关于set,get,didSet和willSet的一些很好的提示,在第250页左右.
如果您的错误仍然存在,请告诉我(如果是这样,您应该在设置此变量以及类标题和内容时发布,可能信息不足.还有,您使用的是xcode6-beta4吗?)