简体   繁体   中英

Add multiple UIImageview in UIScrollview programmatically

UIView *view = nil;

NSArray *subviews = [scrollView subviews];

CGFloat curXLoc = 0;

for (view in subviews)
{
    if ([view isKindOfClass:[UIView class]] && view.tag > 0)
    {
        CGRect frame = view.frame;

        frame.origin = CGPointMake(curXLoc, 0);

        view.frame = frame;


        curXLoc += (kScrollObjWidth);
    }
}

I had placed one Scrollview , within this scroll view i place 5 UIImageview in XIB file

I have one image and one button, whenever I clicked the button the image should be loaded into all the UIImageview s within the UIScrollview programmatically.

and also I used the following coding

for(UIImageView *addview in Scroll)
{

    if([addview isKindOfClass:[UIImageView class]])
    {

        UIImageView *newImage = (UIImageView *)addview;

        newImage.image = [UIImage imageNamed:@"EarP010.jpg"];
    }
}

Try this,

NSMutableArray * imagesArray = [[NSMutableArray alloc]init];

for (int imageCount = 0; imageCount < (noOfImages);imageCount++)
{
 [imagesArray addObject:[UIImage imageNamed:@"localImagePath%d.png",imageCount]];
}

UIScrollView * scrollview = [[UIScrollView alloc]initWithFrame:CGRectMake(0.0,0.0,480.0,960.0)];
scrollview.contentSize = CGSizeMake(scrollview.size.width * (noOfImages),scrollview.frame.size.height);
scrollview.pagingEnabled = YES;

CGFloat xPos = 0.0;

for (UIImage * image in imagesArray) {
@autoreleasepool {
UIImageView * imageview = [[UIImageView alloc]initWithImage:image];
imageview.frame = CGRectMake(xPos, 0.0,scrollview.frame.size.width ,self.scrollView.frame.size.height);
[scrollview addSubview:imageview];
xPos += scrollview.size.width;
}
}

You could add the image views in a while loop if you know how many image view you need.

     UIScrollView *sv = [UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
     ....
     [self.view addSubView:sv];

     int i = 0;
     while(i < numberOfImages){
         i = i + 200;
         UIImageView *i = [UIImageView alloc] initWithFrame:CGRectMake(20, i, 200, 100)]
         ....
         [sv addSubView:i];
       i++;
     }

This is one situation you could use. You will need to know the number of image views you need and what the Y values are on these image views. Much of this code is pseudo code and needs to be filled in.

Use this

NSArray* objects = [[NSBundle mainBundle] loadNibNamed:@"your xib name" owner:nil options:nil];

UIView* mainView = [objects objectAtIndex:0];

for (UIView* view in [mainView subviews]) {
    if([view isKindOfClass:[UIImageView class]])
    {
        UIImageView *iview = (UIImageView *)view;


        iview.image = [UIImage imageNamed:@"your imagename.png"];
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM