【问题标题】:Pass variables into drawRect in swift快速将变量传递给drawRect
【发布时间】:2015-09-09 11:09:15
【问题描述】:

我想快速将颜色数组传递给 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")
    }
}

【问题讨论】:

    标签: ios swift uiview drawrect


    【解决方案1】:

    你的类有颜色作为静态变量,就像类变量一样,它是 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()]
    

    【讨论】:

    • 非常感谢你,你解决了我的问题,我也学到了一些新东西!
    猜你喜欢
    • 2014-11-08
    • 1970-01-01
    • 1970-01-01
    • 2018-04-07
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-19
    相关资源
    最近更新 更多