无法更改视图中绘制的圆的颜色
Can't change color of circle drawn in view
我正在尝试更新我在 UIView
的子 class 中创建的圆的颜色,方法是在 class 中创建一个方法来更新颜色,如下所示,但是颜色不变。
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)
}
我做错了什么?
更新: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 操场上玩耍:
我正在尝试更新我在 UIView
的子 class 中创建的圆的颜色,方法是在 class 中创建一个方法来更新颜色,如下所示,但是颜色不变。
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)
}
我做错了什么?
更新: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 操场上玩耍: