我有一个按钮,我试图在线程完成时设置图像。我的代码似乎只是更改图像按钮毫无用处,但这是为了练习和做更大的事情。
目标:将 b0 的图像设置为 button_x.png
(在项目中找到)。
问题:按钮图像没有改变,如果我在 Storyboard上找到的按钮与 viewController 按钮声明之间建立连接,我会因 -[UIButton setImage:] 而崩溃: 无法识别的选择器发送到实例 0x8b4c270
。
谢谢。
ViewController.h:
@interface ViewController : UIViewController {
IBOutlet UIButton *b0;
Game *instanceOfGame;
}
@property (nonatomic, strong) UIButton *b0;
@property (nonatomic, strong) Game *instanceOfGame;
@end
ViewController.m:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize instanceOfGame;
@synthesize b0;
static NSString *postName = @"123";
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(post:) name:postName object:nil];
instanceOfGame = [[Game alloc] init];
[instanceOfGame start];
}
- (void) post: (NSNotification *) result {
NSNumber *str = [result object];
if (str == 0) {
[self.b0 performSelectorOnMainThread:@selector(setImage: ) withObject:[UIImage imageNamed:@"button_x.png"] waitUntilDone:NO];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
游戏.h:
#import <Foundation/Foundation.h>
@interface Game : NSObject
@property (nonatomic, strong) NSNumber *choice;
@property (nonatomic, strong) NSNotificationCenter *ns;
-(void) start;
@end
游戏.m:
#import "Game.h"
@implementation Game
NSNotificationCenter *ns;
@synthesize ns;
@synthesize choice;
static NSString *postName = @"123";
-(id) init {
if (self = [super init]) {
ns = [NSNotificationCenter defaultCenter];
}
return self;
}
-(void) start {
[self performSelectorInBackground:@selector(loadData) withObject:Nil];
}
-(void) loadData {
choice = 0;
[ns postNotificationName:postName object:choice];
}
@end
最佳答案
UIButton 没有 setImage: 函数,因此抛出异常。
虽然它确实有这个功能:
- (void)setImage:(UIImage *)image forState:(UIControlState)state
尝试替换:
[self.b0 performSelectorOnMainThread:@selector(setImage: ) withObject:[UIImage imageNamed:@"button_x.png"] waitUntilDone:NO];
使用 GCD 调用正确的函数完成类似的实现:
dispatch_async(dispatch_get_main_queue(), ^{
[self.b0 setImage:[UIImage imageNamed:@"button_x.png"] forState:UIControlStateNormal];
});
关于ios - 线程完成时的 Objective C 设置图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22369783/