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
causes draw
to run again, and it sets the fill color back to blue. Try adding a property to your Badge
view to store the desiredColour
:
class Badge: UIView {
var desiredColour: UIColor = .blue
struct mine {
static var p = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 100, height: 100))
}
override func draw(_ rect: CGRect) {
// Drawing code
desiredColour.setFill()
mine.p.fill()
}
func colour() {
desiredColour = .red
self.setNeedsDisplay()
}
}
If you add didSet
to desiredColour
, you can have it call setNeedsDisplay
for you, and then you don't even need the colour
function. So to use it, you just call myBadge.desiredColour = .red
and the view will redraw!
class Badge: UIView {
var desiredColour: UIColor = .blue {
didSet {
self.setNeedsDisplay()
}
}
struct mine {
static var p = UIBezierPath(ovalIn: CGRect(x: 0, y: 0, width: 100, height: 100))
}
override func draw(_ rect: CGRect) {
// Drawing code
desiredColour.setFill()
mine.p.fill()
}
}
Here it is running in a Swift Playground: