簡體   English   中英

以編程方式在UIScrollview中添加多個UIImageview

[英]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);
    }
}

我放置了一個Scrollview ,在這個滾動視圖中我將5個UIImageview放在XIB文件中

我有一個圖像和一個按鈕,每當我點擊按鈕時,圖像應該以編程方式加載到UIScrollview所有UIImageview

我還使用了以下編碼

for(UIImageView *addview in Scroll)
{

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

        UIImageView *newImage = (UIImageView *)addview;

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

試試這個,

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

如果您知道需要多少圖像視圖,則可以在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值。 大部分代碼都是偽代碼,需要填寫。

用這個

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM