I am trying to update the colour of a circle I have created in a subclass of UIView
by creating a method within the class to update the colour as below but the colour does not change.
import UIKit
class badge: UIView {
struct mine {
static var p = UIBezierPath(ovalInRect: CGRectMake(0,0,100,100))
}
override func drawRect(rect: CGRect) {
// Drawing code
UIColor.blueColor().setFill()
mine.p.fill()
}
func colour(whatColour: String) {
UIColor.redColor().setFill()
mine.p.fill()
self.setNeedsDisplay()
}
}
// The above is referenced in view controller with
@IBOutlet weak var myBadge: badge!
// change function colour is called with
myBadge.colour()
// but the colour of the circle does not change (its still filled in blue)
}
What am I doing wrong?
Update: Swift 3 (and Swift 4) syntax:
setNeedsDisplay
causesdraw
to run again, and it sets the fill color back to blue. Try adding a property to yourBadge
view to store thedesiredColour
:If you add
didSet
todesiredColour
, you can have it callsetNeedsDisplay
for you, and then you don't even need thecolour
function. So to use it, you just callmyBadge.desiredColour = .red
and the view will redraw!Here it is running in a Swift Playground: