views:

319

answers:

1

I'm looking more for advice on the correct design for a view.

What I have is a UIScrollView that contains one or more custom Views I have created. My problem is, who reports to the scrollview what it's contentSize should be? I have the following:

UIView  
+-UIScrollView  
  +-CustomView 1 with dynamic height depending on data
  +-CustomView 2 with dynamic Height depending on data

The UIViewController creates new instances of the custom views with data and then adds them as subviews to the UIScrollView. The problem I'm having is how to set the value of the scrollview's contentSize? Right now, I'm not doing that and the contents of the scrollview are clipped with no scrolling possible.

  • Should the custom view call [parent setContentSize:] in its drawRect:?
  • Should the UIViewController query the custom view after creation to get its bounds and then call setContentSize?
  • Should I subclass the UIScrollView to override addSubView to query each subview's height?
  • Is there something else I'm missing?

I hope I explained that properly. I'm new to this and still getting a handle on things.

A: 

The contentSize of the scroll view should be the size of the union of the frames of all your custom views. Whenever the size of a custom view changes, or one is added or removed, the view controller should calculate the new contentSize and apply it.

Setting it from drawRect: could essentially set up an infinite loop.
Using the bounds does not give the coordinates within the parent view.
You could subclass UIScrollView if the custom views do not change size.

drawnonward
I guess that is part of my confusion. Why would the ViewController know the dimensions of the view? (And then be in the position to update the scrollview) Should it know the dimensions? It seems to me that the view is what is doing all of the drawing, so it would be the one true source of its dimensions. Am I wrong on that?
Mike
Yes, each custom view is the source of its own dimensions, and should report an ideal size through sizeThatFits: or just size themselves. But they should not need to know the dimensions of their peers. Some higher level object needs to find the union of the custom views, and lay them out within the scroll view. That could be the view controller or a custom scroll view. I would choose a view controller unless you will have several instances of the custom scroll view.
drawnonward
So basically, the custom view has to be able to calculate its height outside of drawRect? That seems inline with tableviews and cells.
Mike