jxxcarlson
jxxcarlson

Reputation: 333

In Swift, drawRect for custom view is not updating properly

Below is my drawRect function for a simple custom view. When I use

var h: CGFloat = 200

the view displays itself properly: a rectangle part of which is black, part of which is red. But when I use

var h: CGFloat = fractionalHeight*parentViewHeight

all I get is a black rectangle. If fractionalHeight (a property of the view) is 0.5, half of the rectangle should be red. The print statement confirms the fact that h is what I think it should be. Hmmmmm? What's going on?

    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)")

}

Upvotes: 3

Views: 5990

Answers (1)

vacawama
vacawama

Reputation: 154533

I believe you are talking to 2 different OCIndicator instances.

I believe you have an OCIndicator (in your StoryBoard perhaps) hooked up to an IBOutlet in your ViewController.

In viewDidLoad you are creating a second instance of OCIndicator and assigning it to the local variable indicator and you are adding that to your subView which is covering up the first one. But then, you are setting fractionalHeight on self.indicator which is not the same indicator and you are telling that one that it needs to display, but it has been covered up by the one added in viewDidLoad.

So, get rid of:

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

from viewDidLoad and see how that works.

Upvotes: 3

Related Questions