按钮.启用不刷新IOS



我有一个UIViewController从web加载数据,这个过程大约需要15秒,所以我把我长时间运行的进程放在第二个线程上,当第二个线程完成时,我将设置按钮启用或禁用。但是该过程完成后,按钮不会刷新。

#import "ViewController.h"
#import "FunctionNSObject.h"
@interface ViewController ()
@end
@implementation ViewController
NSMutableArray *schoolsAvaliable;
NSDictionary *dict;
NSString *schoolNameCh, *schoolNameEn;
int schoolYear, schoolID;
- (void)viewDidLoad
{
    [super viewDidLoad];
}
-(void)viewWillAppear:(BOOL)animated
{
    //initial set the button disable
    self.button.enabled = NO;
    //2nd thread
    dispatch_queue_t downloadQueue = dispatch_queue_create("loadSchool", NULL);
    dispatch_async(downloadQueue, ^{
        //get avalible school info from JSON
        schoolsAvaliable = [FunctionNSObject loadDataFromWeb:@"http://some web service"];
        //get school year
        schoolYear = [FunctionNSObject getSchoolYear];

        if (schoolsAvaliable.count != 0)
        {
            //select the first row from array
            dict = schoolsAvaliable[0];
            //get the value from dictionary of that row
            schoolID = (int)[[dict objectForKey:@"SchoolId"] integerValue];
            schoolNameCh = [dict objectForKey:@"SchoolName"];
            schoolNameEn = [dict objectForKey:@"SchoolNameEn"];
            self.button.enabled = YES;
            [self.button setNeedsDisplay];
        }
        else
        {
            self.button.enabled = NO;
            [self.button setNeedsDisplay];
        }
        //2nd thread end then
        dispatch_async(dispatch_get_main_queue(), ^{
            //[self.pickerSchool reloadAllComponents];
            self.labelSchool.text = [NSString stringWithFormat:@"%d - %d",schoolYear,schoolYear+1];
            NSLog(@"%d",self.button.enabled);
        });
    });

}

@end

在非主线程上调用相关的UI方法。通常会导致不可预测的行为。
尝试在主线程上调用与UI相关的方法,像这样:

dispatch_async(dispatch_get_main_queue(), ^{
    self.button.enabled = YES;
});  

正如@David注意到的,你不需要调用[set.button setNeedsDisplay],因为调用setEnabled:方法会导致调用这个方法。

最新更新