我正在尝试更新我在子类中创建的圆圈的颜色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)
}
我究竟做错了什么?
更新:Swift 3(和 Swift 4)语法:
setNeedsDisplay
causes 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
to 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 Playground 中运行:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)