我试图通过在类中创建一个方法来更新我在UIView
的子类中创建的圆的颜色,以更新颜色,但颜色不会改变。
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)
}
我做错了什么?
答案 0 :(得分:1)
更新:Swift 3(和Swift 4)语法:
setNeedsDisplay
会导致draw
再次运行,并将填充颜色设置为蓝色。尝试在Badge
视图中添加属性以存储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()
}
}
如果您将didSet
添加到desiredColour
,则可以让它为您调用setNeedsDisplay
,然后您甚至不需要colour
功能。因此,要使用它,只需调用myBadge.desiredColour = .red
,视图就会重新绘制!
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()
}
}
这是在Swift游乐场中运行的: