【问题标题】:UIImageView From NSMutableArray来自 NSMutableArray 的 UIImageView
【发布时间】:2015-12-09 11:20:03
【问题描述】:

我需要根据 NSMutableArray 中的对象数量创建一定数量的 UIImageView。例如,如果这个 NSMutableArray 中有 5 个 UIImage,我如何用这些图像创建 5 个 UIImageView?

谢谢

【问题讨论】:

    标签: objective-c uiview uiimageview nsarray


    【解决方案1】:

    使用NSArraycount属性:

    UIImage *image1 = [UIImage imageNamed:@"img1.png"];
    UIImage *image2 = [UIImage imageNamed:@"img2.png"];
    UIImage *image3 = [UIImage imageNamed:@"img3.png"];
    UIImage *image4 = [UIImage imageNamed:@"img4.png"];
    UIImage *image5 = [UIImage imageNamed:@"img5.png"];
    NSArray *imageArray = @[image1, image2, image3, image4, image5];
    
    NSInteger imageCount = 0;
    NSInteger imageViewYM = 20; // Ensure this is bigger than image height
    
    for (UIImage *image in imageArray) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0, imageViewYM * imageCount, image.size.width, image.size.height)];
        imageView.image = image;
    
        [self.view addSubview:imageView];
        imageCount++;
    }
    

    【讨论】:

    • 谢谢,我已经设置好了。你知道是否有办法让它们为每个 imageView 移动而不是重叠?再次感谢
    • NSInteger 持有基于上下文使用的 UIImageView 计数,例如设置超级视图的框架等。但是 for 循环足以让您访问 UIImages 以创建图像视图。跨度>
    • @Dyllan - 抱歉,我不太明白你的问题。你能改写一下吗?
    • 由于创建了多个 UIImageViews,我如何在它们之间留出空间?目前它正在工作,但它们重叠,我想知道我将如何处理它们之间的间距。再次感谢
    • 很高兴它有帮助:)。你能接受这个答案吗?
    【解决方案2】:

    为所有图像运行一个while循环并为每个图像创建一个新的UIImageView:

    NSArray *imageArray = @[image1, image2, image3];  
    int i = 0;
    while(i < imageArray.count) {
        UIImageView * imageView = [[UIImageView alloc] init];
        imageView.image = [imageArray objectAtIndex:i];
        imageView.frame = CGRectMake(0, 0, 50, 50);
        imageView.tag = i;
        [self.view addSubview:imageView];
        i++;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多