I'm drawing a grid of data in a UIView with
drawRect, of which I won't know the final size when the UIView is created because the number of columns and rows is dynamic. Sure I could do the calculations before creating the UIView, but that doesn't really make sense, because I'll also be doing those calculations in the UIView subclass, and would rather not have to extract that.
So how do I handle this? Do I init with a very large frame and adjust it after drawRect is done?
I will also be setting this view as the content of a UIScrollView in case its too large to be viewed in the area allotted for it.
The view I'm going to be drawing looks something like this:
contentSizeto that size.
The key concept is: Separate the ideas of "determine how large my view's stuff is" and "draw my view's stuff". Right now, you are doing the size computation while you draw, but you need to be able to do it earlier.
If you want to get fancy, you could look into overriding
layoutSubviews in a superview of your view -- that would be a good place to check if the view's desired size has changed, and then update the view's size and the scroll view's
contentSize. But it isn't necessary to do that to start.
layoutSubviewsgets called more than once. See: http://stackoverflow.com/a/20131528/14322 - Brenden 2013-11-21 20:50
Perhaps others have another solution but I think that in your case I would override setFrame: and call setNeedsDisplay so that drawRect will be called after your frame changes. Have you tried this approach already?