简体   繁体   中英

Can't Change UIButton attributed title

I'm trying to change the attribute title of a button. The change should take place after an NSURLConnection request, hence it's placed in the completion handler.

When the app opens, the code works well, however at some point in code I want to change the title again but it's not changing. Here is what I am doing:

[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        NSString *city = [cities firstObject];
        NSMutableAttributedString *subTitleOne = [[NSMutableAttributedString alloc] initWithString:@"something "];
        NSMutableAttributedString *subTitleTwo = [[NSMutableAttributedString alloc] initWithString:city.uppercaseString];
        [subTitleTwo addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:0.1 green:0.8 blue:0.44 alpha:1]  range:NSMakeRange(0, [NSString stringWithFormat:@"%@", city.uppercaseString].length)];
        [subTitleOne appendAttributedString:subTitleTwo];

        [_sidebarButton setAttributedTitle:subTitleOne forState:UIControlStateNormal];
        [_sidebarButton.titleLabel setAdjustsFontSizeToFitWidth:YES];
    }];
}];

I'm exiting the block on the main queue since it's a UI change and I don't want it to be delayed. Now when I run the code later on, the title doesn't change but if I tap the button it changes. What's wrong with it?

I found out the problem. the button is in the navigation bar and when tapped it opens the side bar. When the user swipes it also opens the sidebar however the button is being stuck on Selected. Hence since the Attribute title is set on Normal it won't change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM