Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set content size of UIScrollView dynamically

I got question about UIScrollview.

The story is I have a UIView named ChartsView which I re-draw it myself by override method drawRect(). The content of drawing was generated dynamically. So I do not know its size until runtime. The question is how/where can I set its super view's (scrollView) content size dynamically?Any idea about that?

    - (void)viewDidLoad
    {
        [super viewDidLoad];

// not this way. it's fixed size.....
        ChartsView *chartsView = [[ChartsView alloc]initWithFrame:CGRectMake(0, 0, 320, 800)]; 

        self.scrollView.contentSize = chartsView.frame.size;

        [self.scrollView addSubview:chartsView];

    }
like image 216
Roger Lee Avatar asked May 09 '12 15:05

Roger Lee


3 Answers

One more easy way

- (void)viewDidLoad {     float sizeOfContent = 0;     UIView *lLast = [scrollView.subviews lastObject];     NSInteger wd = lLast.frame.origin.y;     NSInteger ht = lLast.frame.size.height;      sizeOfContent = wd+ht;      scrollView.contentSize = CGSizeMake(scrollView.frame.size.width, sizeOfContent); } 
like image 113
IOS Rocks Avatar answered Sep 24 '22 20:09

IOS Rocks


It is not 100% guaranteed that the last object in scrollView.subviews array will return the highest y-origin object in your scroll view. The subviews array is arranged by Z-Index (i.e the last object in the subviews array will be the object stacked the highest and will be the top-most subview in the scroll view's subviews. Instead it is more accurate to use a basic sort function to iterate through the subviews and get the object with the highest y-origin.

Swift 4

extension UIScrollView {
    func updateContentView() {
        contentSize.height = subviews.sorted(by: { $0.frame.maxY < $1.frame.maxY }).last?.frame.maxY ?? contentSize.height
    }
}

Usage (in viewDidLayoutSubviews or whenever your content size updates):

myScrollView.updateContentView()
like image 35
Charlton Provatas Avatar answered Sep 20 '22 20:09

Charlton Provatas


swift (2.0)

@IBOutlet weak var btnLatestButton: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()

    let height = btnLatestButton.frame.size.height
    let pos = btnLatestButton.frame.origin.y
    let sizeOfContent = height + pos + 10
    scrollview.contentSize.height = sizeOfContent

}

Above ofcourse is when you just have a fixed amount of views on your scrollview. IOS Rocks method is available but was not good for me, created more space then I needed.

    let lastView : UIView! = scrollview.subviews.last
    let height = lastView.frame.size.height
    let pos = lastView.frame.origin.y
    let sizeOfContent = height + pos + 10
    scrollview.contentSize.height = sizeOfContent
like image 32
CularBytes Avatar answered Sep 21 '22 20:09

CularBytes