Reputation: 31283
I'm trying to convert this Objective-C class to Swift.
Below is what I'm done so far.
import UIKit
public class CustomColoredAccessory: UIControl {
var accessoryColor = UIColor()
var highlightedColor = UIColor()
required public init(coder aDecoder: NSCoder!) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.clearColor()
}
override public func drawRect(rect: CGRect) {
let x: CGFloat = CGRectGetMaxX(bounds) - 3
let y: CGFloat = CGRectGetMaxY(bounds)
let R: CGFloat = 4.5
let ctxt = UIGraphicsGetCurrentContext()
CGContextMoveToPoint(ctxt, x - R, y - R)
CGContextAddLineToPoint(ctxt, x, y)
CGContextAddLineToPoint(ctxt, x - R, y + R)
CGContextSetLineCap(ctxt, kCGLineCapSquare)
CGContextSetLineJoin(ctxt, kCGLineJoinMiter)
CGContextSetLineWidth(ctxt, 3)
if highlighted == true {
highlightedColor.setStroke()
} else {
accessoryColor.setStroke()
}
CGContextStrokePath(ctxt)
}
public class func accessoryWithColor(color: UIColor) -> CustomColoredAccessory {
var ret = CustomColoredAccessory(frame: CGRectMake(0, 0, 11, 15))
ret.accessoryColor = color
return ret
}
}
In the origin Objective-C code, there's one setter and two getters for the two properties.
- (void)setHighlighted:(BOOL)highlighted {
[super setHighlighted:highlighted];
[self setNeedsDisplay];
}
- (UIColor *)accessoryColor {
if (!_accessoryColor) {
return [UIColor blackColor];
}
return _accessoryColor;
}
- (UIColor *)highlightedColor {
if (!_highlightedColor) {
return [UIColor whiteColor];
}
return _highlightedColor;
}
I noticed that property setters and getters are gone i Swift. At least a little different.
I tried adding the setter to highlightedColor
like this,
var highlightedColor = UIColor() {
set {
setNeedsDisplay()
}
}
But I get this error at the set
line - Use of unresolved identifier 'set'
Can someone please tell me how to correct this error? I can't figure it out.
Thank you.
Upvotes: 3
Views: 3866
Reputation: 1524
The setter and getter are both placed in the variable declaration:
var highlightedColor: UIColor {
set {
//custom setter
}
get {
//custom getter
}
}
You would also need to include the get
. Anyway, if you want to call setNeedsDisplay()
you would be better off by using a "property observer" like so:
var highlightedColor: UIColor {
didSet {
setNeedsDisplay()
}
}
For more info take a look at Swift Properties
Upvotes: 6