简体   繁体   中英

How Do I Force Redrawing (drawRect) of a SubView When it Changes Dimensions?

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

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)

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 NSTextContainer s, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM