开发者

Refreshing parent UIScrollView contentSize after subview's drawRect

I have a UIScrollView, with a UIView in it.

I don't know the size of the subview until everything in it that needs to be displayed has been, and this can change on later drawings. (It has tables, text etc. that are added bit by bit). So, I need to update the scroll view's content size at the point that the subview's drawRect completes.

Is there a good way to trigger the required [myScrollView setContentSize] & [mySubView setNeedsDisplay] (this calls drawRect so I'll take steps to avoid infinite loops) after the drawRect, or any other solution that actually works for this situatio开发者_开发百科n?

It seems to need setNeedsDisplay called on the subview before the content size change is acted on. All I have to do is set the setContentSize from the sub-view's drawRect then I press a button that triggers the setNeedsDisplay, the contentSize then refreshes fine. So I could just set a timer and wait for the next run loop to do the setNeedsDisplay? But it's an awful hack. Also I'm guessing resizing the content size in code called from the sub-view's drawRect is a no-no if UIKit relies on the view hierarchy remaining constant while it is in the middle of drawing the view hierarchy.


You could use an NSNotification.

At the end of your drawing code, post a notification.

        [[NSNotificationCenter defaultCenter] 
                      postNotificationName:@"drawingLoopDone_Notification"
                                    object:nil];

Add the appropriate view controller as an NSObserver of the notification.

  [[NSNotificationCenter defaultCenter] 
          addObserver:self 
             selector:@selector(setNeedsDisplay)
                 name:@"drawingLoopDone_Notification" 
               object:nil];

After the notification is received (or in your viewDidUnload), clean up the notification listener like this:

    [[NSNotificationCenter defaultCenter] 
                removeObserver:self name:@"drawingLoopDone_Notification" object:nil];


I've just gone with...

[theView performSelector:@selector(someSelector) withObject:nil afterDelay:0.0];

...which at least makes the hack work, because it doesn't call the selector till after drawRect has finished, so the setNeedsDisplay (leading to another drawRect, with a check to avoid looping) that is apparently needed is not cancelled.

I'd still love to hear if there's a more standard way to update the scroll view's content size when you don't know the size of it's subview until it's been drawn.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜