Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios Can';t更改视图中绘制的圆的颜色_Ios_Swift_Uiview - Fatal编程技术网

Ios Can';t更改视图中绘制的圆的颜色

Ios Can';t更改视图中绘制的圆的颜色,ios,swift,uiview,Ios,Swift,Uiview,我正在尝试更新我在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

我正在尝试更新我在
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
使
draw
再次运行,并将填充颜色设置回蓝色。尝试将属性添加到
徽章
视图中,以存储
所需颜色

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
添加到
desiredColor
,您可以让它为您调用
setNeedsDisplay
,然后您甚至不需要
color
功能。因此,要使用它,只需调用
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()
    }
}

在这里,它在一个快速的操场上奔跑:


非常感谢这正是我想要的(因为我认为我的错误是对绘图工作原理的根本性误解)。我一直收到CGContextSetFillColorWithColor:invalid context——你能更新这个答案吗