【问题标题】:Set Image of Custom UIView from ViewController从 ViewController 设置自定义 UIView 的图像
【发布时间】:2014-08-08 03:08:17
【问题描述】:

我正在尝试创建这样的应用:


(来源:topmobiletrends.com)

每个视图都为 JSON 数组中的照片中的每个视图显示一个图像。

我已经成功设置并下载了图像数组,并将它们设置在UIImageView 中,并带有NSURLRequest 和SDWebImage。

我创建了一个带有图像视图的UIView,以测试我的ViewController(Storyboard) 中的代码,一切正常。但是,当我尝试创建一个UIView 以编程方式循环时,它显示为空白,没有ImageView。我不确定我做错了什么。

这是我的ViewController.m 代码

for (NSObject *photo in photos) {

     UIView *dView = [[UIView alloc]initWithFrame:CGRectMake(160,250,258,229)];
        dView.backgroundColor = [UIColor whiteColor];

    dispatch_async(dispatch_get_main_queue(),^{
        UIImage *image = [UIImage imageWithData:data];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
        myImage.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageURL]];

        //Get image from url
        [self.imageView setImageWithURL:imageURL];
        [self.myImage addSubview:imageView];

        priceLabel.text = [[[jsonDictionary objectForKey:@"site"] objectAtIndex:index] objectForKey:@"price"];
        [imageView addSubview:dView];

    });
        }

        }];

[task resume];

   }

【问题讨论】:

  • 为什么要为每张图片创建一个新的 UIView?
  • @raki 创建一个可重用的 xib(自定义 UIView)会更好吗?
  • 一旦在下面观察我的答案......:)

标签: ios objective-c uiview uiimageview xib


【解决方案1】:

您正在将 dView 添加为图像视图的子视图,可能是 [dView addSubview:imageView];

【讨论】:

  • 刚试了一下,视图还是显示为空白。 :(
  • 现在视图显示一个图像,但每个视图都显示相同的图像。我需要每个视图为数组中的每个对象显示一个新图像。
  • 实际上它现在可以工作了! :) 除了您的解决方案之外,我还删除了一个不必要的 for 在所示循环之前的循环,并且所有图像都通过了! :) 谢谢你帮助我。我希望我能 +1,但我还需要 5 个声望。 ://
【解决方案2】:

试试这个。主要问题是您没有为图像视图设置框架

 for (NSObject *photo in photos) {
    //UIView *dView = [[UIView alloc]initWithFrame:CGRectMake(160,250,258,229)];
    //dView.backgroundColor = [UIColor whiteColor];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(160,250,258,229)];
    [self.myImage addSubview:imageView];

    priceLabel.text = [[[jsonDictionary objectForKey:@"site"] objectAtIndex:index] objectForKey:@"price"];
    //[imageView addSubview:dView];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"URL"]];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (imgData) {
                [imageView setImage:[UIImage imageWithData:imgData]];
            }
        });
    });
    }

【讨论】:

  • 视图仍然显示为空白。 :( 没有图像视图或标签 (priceLabel)。
  • 看看你的网址是否正确
  • 是的,网址很好。它显示在我在 Storyboard 中创建的视图上。但是其他的观点,什么都没有。
猜你喜欢
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多