将变量传递到swift中的drawRect

问题描述:

我想将swift中的颜色数组传递给drawRect,我该怎么做? (我得到了很多错误..)将变量传递到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 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()] 
+0

非常感谢你的人,你解决了我这个问题,我也学到了一些新东西! –