我尝试分配通过加载的图像
[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;
只要我拍摄本地镜像并像这样分配 ImageView ,这就可以工作:
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];
无论如何,我现在不再收到错误了,但是图像没有出现......
最佳答案
这应该异步工作
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;
关于ios - 来自 URL 的图像为 rightBarButtonItem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12464885/