在 swift 中将变量传递到 drawRect

Pass variables into drawRect in swift

我想将颜色数组传递到 swift 中的 drawRect,我该怎么做? (我遇到了很多错误..)

class GradientColorView : UIView {

    static let colors : NSArray = NSArray()

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    class func initWithColors(colors :NSArray) {

    }

    override func drawRect(rect: CGRect) {

        println(self.colors)
        println("drawRect has updated the view")
    }
}

您的 class 将颜色作为静态变量,就像 class 变量一样,它是 let ,这意味着它是不可变的常量。如果您希望它是可修改的,则需要将该 let 更改为 var。因此,您无法从实例访问它。我建议您将其更改为实例变量,这样可以在颜色发生变化时轻松进行绘图调用。

你可以这样做,

class GradientColorView : UIView {

    var colors : NSArray = NSArray() {
        didSet {
            setNeedsDisplay()
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
    }

    class func initWithColors(colors :NSArray) {

    }

    override func drawRect(rect: CGRect) {

        println(self.colors)
        println("drawRect has updated the view")
    }
}

然后您可以从 gradientView 实例更新颜色,这将再次重绘它,

let gradientView = GradientColorView(frame: CGRectMake(0, 0, 200, 200))
gradientView.colors = [UIColor.redColor(), UIColor.orangeColor(), UIColor.purpleColor()]