Question

I have a UIView that contains a row of subclasses of UIView. The subclass has overridden drawRect: and has set contentMode = UIViewContentModeRedraw.

As the user squashes and stretches the parent container the child views squash and stretch. As the shape change occurs I would like to have drawRect called repeatedly to change the contents of the child views. So far I have been unsuccessful. What is the correct way to do this?

Cheers,

Doug

Was it helpful?

Solution

In Cocoa, you rarely (if ever) call drawRect - you just mark the region or view as needing update, and it will be scheduled for redrawing. This allows redraws for multiple invalidations to be collapsed together.

For Cocoa Touch, you want either [view setNeedsDisplay], or setNeedsDisplayinRect:(CGRect)

OTHER TIPS

You need to call [view setNeedsLayout], this should cause the subviews to receive a drawRect: call if the layout changes. I haven't tested this, however.

This solution is a little crazy, but it makes logical sense, and has a great visual result. I'm working with a NSLayoutManager and a couple NSTextContainers, laying out text in two columns. Because I'm using multiple text containers (and I'm not sure I want multiple UITextView), I'm overriding the draw(rect: CGRect) method of MyDrawingView: UIView.

The problem is that using self.contentMode = .redraw still results in some minor stretching on rotation--significant enough to be a deal-breaker.

I noticed that setting contentMode = .left, or even contentMode = .scaleAspectFit was close to what I wanted, in terms of pixel-perfect rotation. But obviously, I wasn't getting the draw call I needed.

So--I overrode layoutSubviews(), switched the contentMode to .scaleAspectFit, called super.layoutSubviews(), and then switched it back. :P

override func layoutSubviews() {
    self.contentMode = .scaleAspectFit

    super.layoutSubviews()
    self.contentMode = .redraw
}

It is...perfect.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top