Cris
Cris

Reputation: 12194

How to correctly work with UIScrollView and UIPageControl?

I have a UIScrollView that I would like to use with a UIPageControl to have different pages to swipe horizontally. I need to add a UITextView and a number of UIImageView for every page. In my ViewController I call a webservice and, when data arrive, I add items as follows:

for(int i=0;i<[arrData count];i++) {
    NSString *body=@"Dummy text";

    CGRect frame;

    frame.origin.x = self.scrollView.frame.size.width * i;
    frame.origin.y = 0;
    frame.size.width = self.scrollView.frame.size.width;
    frame.size.height = 40; //vedere landscape

    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    [label setText:body];
    label.numberOfLines=0;
    [label sizeToFit];
    label.autoresizingMask=UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.scrollView addSubview:label];

    [label setBackgroundColor:[UIColor whiteColor]];
    [self.scrollView addSubview:label];
    int y_pos=label.frame.size.height+10;
    int x_pos=0;
    for(int img=0; img<[[[arrData objectAtIndex:i]objectForKey:@"images"] count]; img++) {
        NSString *imageURL=[[[[arrData objectAtIndex:i] objectForKey:@"images"] objectAtIndex:img] objectForKey:@"fn"];

        NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]];
        UIImage *image = [UIImage imageWithData:imageData];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
        [imageView setFrame:CGRectMake(self.scrollView.frame.size.width * i+img*100, y_pos, image.size.width, image.size.height)];
        [self.scrollView addSubview:imageView];

    }

}
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * [arrData count], self.scrollView.frame.size.height);

It runs fine in portrait, but when the device is rotated, obviously, the layout is ruined ... which is the best way to work with a ScrollView with PageControl? Do I have to handle rotation and change the distance between the inserted items or (as I think) is there a better way to build everything?

Upvotes: 1

Views: 595

Answers (1)

Vishal Singh
Vishal Singh

Reputation: 4480

yes you have to set your scrollviews frame again every time orientation changes, because flexible width stretches the width of scrollview from both sides in landscape mode,so its contents get overlapped and causes problem when you have horizontal scrolling. one thing you can do is set you scrollview's auto resizing mask to flexibleRightMargin|flexibleLeftMargin. it will keep the contents of your scrollview at the center but scrolling will not look clean.

Upvotes: 1

Related Questions