在Swift中,自定义视图的drawRect未正确更新

时间:2014-06-14 22:40:17

标签: ios uiview swift drawrect

下面是我的drawRect函数,用于简单的自定义视图。当我使用

var h: CGFloat = 200

视图正确显示:矩形部分为黑色,其中一部分为红色。但是当我使用

var h: CGFloat = fractionalHeight*parentViewHeight

我得到的只是一个黑色矩形。如果fractionalHeight(视图的属性) 是0.5,矩形的一半应该是红色。印刷声明证实了这一事实 那是我认为应该是的。 Hmmmmm?发生了什么事?

    override func drawRect(rect: CGRect)
{
    var ctx = UIGraphicsGetCurrentContext()

    CGContextClearRect(ctx, rect);

    let parentViewBounds = self.bounds
    let parentViewWidth = CGRectGetWidth(parentViewBounds)
    let parentViewHeight = CGRectGetHeight(parentViewBounds)
    println ("w,h = \(parentViewWidth),\(parentViewHeight) ")

    // CGContextClearRect(ctx, rect);

    CGContextSetRGBFillColor(ctx, 0.0, 0.0, 0.0, 1); // black
    CGContextFillRect(ctx, CGRectMake(0, 0, parentViewWidth, parentViewHeight));

    println("in drawRect, fractionalHeight = \(fractionalHeight)")

    var h: CGFloat = 200 // fractionalHeight*parentViewHeight

    CGContextSetRGBFillColor(ctx, 1.0, 0.0, 0.0, 1); // red
    CGContextFillRect(ctx, CGRectMake(0, 0, parentViewWidth, h))
    println("in drawRect, h = \(h)")

}

1 个答案:

答案 0 :(得分:3)

我相信您正在与2个不同的OCIndicator实例进行对话。

我相信你有一个OCIndicator(也许在你的StoryBoard中)与ViewController中的IBOutlet相连。

viewDidLoad中,您正在创建OCIndicator的第二个实例,并将其分配给本地变量indicator,并将其添加到覆盖第一个subView的{​​{1}}。但是,你在fractionalHeight self.indicator上设置的viewDidLoad不是同一个指标而是你要告诉它需要显示的那个,但它已被{{1}中添加的那个覆盖了}。

所以,摆脱:

var indicator: OCIndicator = OCIndicator(frame: CGRectMake(10, 30, 50, 400))
self.view.addSubview(indicator)

来自viewDidLoad,看看它是如何运作的。