来自URL的图像为rightBarButtonItem

时间:2012-09-17 18:10:14

标签: ios iphone uiimage uinavigationbar uibarbuttonitem

我尝试分配通过

加载的图像
[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:下面是将图像添加到导航栏的原始问题:how to display an image in the navigation bar of an iPhone application?

修改 这是代码中的错误: 应该是这样我猜:

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

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

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:0)

知道了。如果这个代码在一个单独的线程中,我猜这个视图已经加载后无效。如果我把它简单地告诉vieDidLoad那么它可以工作......

一旦你在这里发帖,你就会得到启发...... ^^