【问题标题】:UIBarButtonItem image not setUIBarButtonItem 图像未设置
【发布时间】:2014-02-15 16:21:48
【问题描述】:

我有一个很奇怪的问题。我正在 AFNetworking 的完成块内初始化一些 UI 元素,其中只有一个 (UIBarButtonItem) 未初始化。这是我的代码,位于viewDidLoad:

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

[m_httpClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

     NSError* error;
     self.m_pointData = [NSJSONSerialization
                        JSONObjectWithData:responseObject
                        options:kNilOptions
                        error:&error];

     [self InitializeFields];
 }
 failure:^(AFHTTPRequestOperation *operation, NSError *error)
 {
     NSLog(@"Error in get point response: %@", error);
 }];

[operation start];

}

我在 InitializeFields 中进行初始化,代码如下:

self.m_placeName.text = [self.m_pointData objectForKey:@"name"];

self.m_placeLocation.text = [self.m_pointData objectForKey:@"city"];

NSArray* comments = [self.m_pointData objectForKey:@"comments"];

const int commentsCount = [comments count];

self.m_commentsCount.text = [NSString stringWithFormat:@"%d", commentsCount];

self.m_scrollView.m_address.text = [self.m_pointData objectForKey:@"address"];
self.m_scrollView.m_email.text = [self.m_pointData objectForKey:@"email"];
self.m_scrollView.m_phone.text = [self.m_pointData objectForKey:@"tel"];
self.m_scrollView.m_link.text = [self.m_pointData objectForKey:@"website"];

self.m_rightBtn.image = [UIImage imageNamed:@"favorite_star_inactive.png"];

只有最后一行 - self.m_rightBtn.image = [UIImage imageNamed:@"favorite_star_inactive.png"]; - 不起作用。当我将其移至viewDidLoad 时,它可以工作。有完成块的东西,但我不知道是什么。

【问题讨论】:

    标签: ios objective-c afnetworking objective-c-blocks uibarbuttonitem


    【解决方案1】:

    我可以假设这个块不在主线程中。 尝试在主线程中执行此操作:

    dispatch_async(dispatch_get_main_queue(), ^{
            //update button
        });
    

    下一个假设是,当您在块中访问图像时,图像尚未初始化。 添加检查:

    if (!self.m_rightBtn.Image) {
        self.m_rightBtn.Image = [UIImage new];
    }
    

    【讨论】:

    • UI 控件的其余部分工作,主线程没有问题,完成块在那里工作。条形按钮项目图像有问题。标签文本等工作正常。
    • 你真的检查了 nil 吗?
    • 是的@Roma,它不是零。
    • 如果您的 AFNetworking 代码在视图中并加载尝试将其移动到 viewDidAppear。我现在认为这是一种不好的方法,但是为了过期而让我们这样做。我认为 uiimage 我们在 viewdidload 中还没有准备好
    【解决方案2】:

    UI 事情应该发生在主线程上,而不是辅助线程上(可能是完成块)。

    在这个里面做 UI 的东西:

    dispatch_async(dispatch_get_main_queue(), ^{
        // This block will be executed asynchronously on the main thread.
    });
    

    一切都会好起来的。有更多细节可以找到in this related question & answer

    【讨论】:

    • 错过了 AFNetworking 的完成块在主线程上工作,AFNetworking 保证,我也检查过。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-29
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    • 1970-01-01
    • 2013-01-21
    • 1970-01-01
    相关资源
    最近更新 更多