0

我尝试分配通过加载的图像

[UIImage imageWithData: [NSData dataWithContentsOfURL:imageUrl]];

到我的导航栏。这是我所拥有的:

   //Loading Image from Url and adding it to navigationbar
    NSString *urlString = [NSString stringWithFormat:@"http://someurl.com/%@.gif",imageId];
    NSURL *imageUrl = [NSURL URLWithString:urlString];
    UIImage *myImage = [UIImage imageWithData: [NSData dataWithContentsOfURL:imageUrl]];
    UIButton* button = (UIButton *) myImage;
    UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = buttonItem;

只要我拍摄本地图像并像这样分配图像视图,这就会起作用:

UIButton* button = (UIButton *) [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"myLocalImage.png"]];

我得到的错误是:*** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[UIImage _setAppearanceIsInvalid:]:无法识别的选择器发送到实例 0x6876df0”

有人可以帮忙吗?(或者这是否太讨厌了?)非常感谢!

Ps:这里是添加图像到导航栏的原始问题:如何在iPhone应用程序的导航栏中显示图像?

编辑: 代码中有一个错误:我猜应该是这样的:

UIButton* button = (UIButton *) [[UIImageview alloc] initWithImage:myImage];

无论如何,我现在不再收到错误,但图像没有出现......

4

2 回答 2

1

这应该异步工作

UIButton *button = [UIButton alloc] init];
UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button]; 
self.navigationItem.rightBarButtonItem = barButtonItem;

__block UIImage *image;
// create a dispatch queue to download your image asynchronously
dispatch_queue_t downloadQueue = dispatch_queue_create("image downloader", NULL);
// show network activity indicator
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
 dispatch_async(downloadQueue, ^{
        image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageUrl]];
        // dispatch to the main queue
        dispatch_sync(dispatch_get_main_queue(), ^{
                // set your button's image
                [button setImage:image forState:UIControlStateNormal];
            });
        }
});
    dispatch_release(downloadQueue);
// hide network activity indicator
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
于 2012-09-17T18:36:56.570 回答
0

知道了。有这个代码在一个单独的线程中,我想这在视图已经加载后不起作用。如果我对 vieDidLoad 说得很清楚,那么它可以工作......

只要你在这里发帖,你就会得到启发...... ^^

于 2012-09-17T18:20:06.743 回答