ios - 来自 URL 的图像为 rightBarButtonItem

标签 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;

只要我拍摄本地镜像并像这样分配 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/

相关文章:

iphone - 如何使 subview 随其父 View 自动调整大小?

iphone - UITextField rightView 上的触摸事件

objective-c - 在 XCODE 中简单调整 UIImage 的大小

ios - 从 ios 应用程序的 SWIFT 中的自定义单元格按钮转到另一个 View

iphone - 从另一个选项卡重新加载 UITableView

iOS Theos Hook 并设置 ivar/property

ios - 删除 UINavigationBar 上的背景图片

ios - 从 iOS 上的两个 jpeg 加载 RGBA 图像 - OpenGL ES 2.0

iphone - 倒数计时器不会停在 0

ios - matchedGeometryEffect 动画效果不流畅