iOS根据用户输入加载图像

时间:2011-07-27 14:44:14

标签: objective-c ipad ios4

对于Objective-C和iOS开发(来自PHP)相当新,我有一个相对简单的问题,我似乎无法找到答案:

我正在关注拆分视图设计的示例,其中当用户单击主视图中的项目时,网页将加载到详细信息视图中。我完成了所有这些工作,但想用Web视图替换图像。所以我修改了应用程序以加载UIImage而不是WebView。我正在寻找的是相当于这段代码:

NSString *urlString = [pagesAddress objectAtIndex:indexPath.row];
NSURL *url = [NSURL URLWithString:urlString];

// these 2 is where I get lost with the images.
NSURLRequest = *request = [NSURLRequest requestWithURL:url];
[detailViewController.webView loadRequest:request];

我想出了这个:

NSString *imageName = [pagesAddress objectAtIndex:indexPath.row];
UIImage *myImage = [UIImage imageNamed:imageName];

// missing the last 2 calls: one to tell Xcode that it's an image "request" I want and the second to load the actual image (based on it's name that is already in an array) into the ImageView.

感谢。

PS

我试过了:

NSString *imageName = [pagesAddress objectAtIndex:indexPath .row];
[detailViewController.imageView setImage:[UIImage imageNamed:imageName]]; 

它只显示第一张图片,然后在我尝试显示最后一张图片时崩溃。

3 个答案:

答案 0 :(得分:0)

最后,当我修改代码时,解决方案是那两行:

NSString *imageName = [pagesAddress objectAtIndex:indexPath.row];
[detailViewController.imageView setImage:[UIImage imageNamed:imageName]];

请注意,我必须更改setImage以将NSString转换为UIImage或Xcode会抱怨。事实证明它崩溃了,因为在我有图像名称的数组中,我将3个图像放入一个条目(基本上我忘记了逗号!)所以它超出了范围。

添:

你给我的这条线

UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];

是不必要的,因为我已经创建了一个视图,它将创建另一个我从未使用过的视图。另外,如果我已经有一个UIImage占位符,用CGRect替换它似乎有点过分了吗?

无论如何,它现在有效,我非常感谢所有的帮助。使用Objectve-C开发iPad是一条非常棘手的道路,我希望我会更多地向你们提问。

干杯。

答案 1 :(得分:-1)

试试这个:

UIImage *myImage = [[UIImage alloc] initWithData:[NSData dataWithConentsOfURL:[NSURL URLWithString:urlString];
// don't know if you already got the following?
UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
[imageView setImage:myImage];
[self.view addSubview:imageView];

第一行是同步(=阻塞),因此在制作中,您应该使用- [NSURLRequest start](但这有点复杂)。


或者将其用于本地图片:

UIImage *myImage = [UIImage imageNamed:imageName];
// Now, follow the same steps as in the first code-example, just skip the first line.

答案 2 :(得分:-1)

试试这个(在iOS 4.0及更高版本中):

// Execute a block of code on a background thread.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
               ^(void) 
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    UIImage* image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
    // When IO is done and image created, set it on the main thread.
    dispatch_async(dispatch_get_main_queue(), 
                   ^(void) 
    {
        imageView.image = image;
    });
    [pool release];
});
相关问题