iphoneobjective-ciosipadxcode4

How to achieve this in an UIScrollView?


I want to display a list of items inside a UIScrollView , here for some items i'm having an images and some won't. The items having image have to be displayed along with image and the others just as a list of items, how can I achieve this? I mean, how to take care of contentSize, offset and all.

Any help is appreciated in advance.


Solution

  • It really depends of what you want to achieve. You have to take in consideration, that sometimes is just better to have a UITableView with some custom UITableViewCell (for memory purposes).

    Ok, so lets assume you want a UIScrollView with a vertical scroll. You will have items with some random images and others with no image at all. What you have to do, is just keep adding your items one after another inside your UIScrollView. You can do this with a while cycle. The only thing you have to pay attention is the measures of your items. So lets assume you have items with 140 of height. You can do something like this (I did not compiled this code):

    float yReference=0.0f;  
    while(MyItem *item in arrayOfItems){
       [myScroll addSubview:item.view];
       item.view.frame=CGRectMake(0.0f, yReference+20.0f, item.view.frame.size.width,   item.view.frame.size.height);
       yReference+=140.0f;
    }
    

    Ok so now you have all your items added to your UIScrollView with space of 20.0f between them. After the while, you just set the correct contentSize of your UIScrollView:

    myScroll.contentSize=vReference+20.0f;
    

    (I added again 20.0f just to have a bit of space at the end)

    You can check this tutorial if you need more help. Although he is adding the items horizontally the logic is the same.