Joris
Joris

Reputation: 6306

View drawRect only called after delay

I made a UIView subclass that implements custom drawing. Here is the code (please don't mind that this could be done by a UIImageView. I stripped the code of all extras just to show the problem)

@IBDesignable
class TPMSkinnedImageView: UIView {
    private var originalImage:UIImage?
    private var skinnedImage:UIImage?

    @IBInspectable var image: UIImage? {
        set {
            originalImage = newValue

            if(newValue == nil) {
                skinnedImage = nil
                return
            }

            skinnedImage = originalImage!

            self.invalidateIntrinsicContentSize()
            self.setNeedsDisplay()
        }

        get {
            return originalImage
        }
    }

    override func draw(_ rect: CGRect) {
        let context:CGContext! = UIGraphicsGetCurrentContext()
        context.saveGState()
        context.translateBy(x: 0, y: rect.height)
        context.scaleBy(x: 1, y: -1)
        context.draw(skinnedImage!.cgImage!, in: rect)
        context.restoreGState()
    }

    override var intrinsicContentSize: CGSize {
        if(skinnedImage != nil) {
            return skinnedImage!.size
        }

        return CGSize.zero
    }
}

I instantiate this view in a viewcontroller nib file and show the viewcontroller modally.

What happens is is that the draw method only gets called when the parent view has been on screen for about 20 seconds.

I checked the intrinsicContentSize and it does not return .zero

This is what the stack looks like once it is called:

enter image description here

Any idea what could be causing this?

Upvotes: 1

Views: 245

Answers (1)

Duncan C
Duncan C

Reputation: 131501

Try calling setNeedsDisplay() on your view in your view controller's viewWillAppear()

Upvotes: 1

Related Questions