以编程方式在UIScrollview中添加多个UIImageview

时间:2013-01-27 06:16:21

标签: ios iphone objective-c uiscrollview uiimageview

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);
    }
}

我放置了一个Scrollview,在此滚动视图中我将5 UIImageview放在XIB文件中

我有一个图像和一个按钮,每当我点击按钮时,图像应该以编程方式加载到UIImageview内的所有UIScrollview

我还使用了以下编码

for(UIImageView *addview in Scroll)
{

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

        UIImageView *newImage = (UIImageView *)addview;

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

3 个答案:

答案 0 :(得分:3)

试试这个,

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;
}
}

答案 1 :(得分:1)

如果您知道需要多少图像视图,则可以在while循环中添加图像视图。

     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++;
     }

这是您可以使用的一种情况。您需要知道所需的图像视图数量以及这些图像视图中的Y值。大部分代码都是伪代码,需要填写。

答案 2 :(得分:1)

使用此

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"];
    }
}