我有一个按钮,我正在尝试设置线程完成时的图像。我的代码似乎没有用,只是更改图像按钮,但这是为了练习并进行更大的事情。
目标:将b0的图像设置为button_x.png
(在项目中找到)。
问题:按钮图像没有改变,如果我在故事板上找到的按钮与viewController按钮声明之间建立了连接,我的-[UIButton setImage:]: unrecognized selector sent to instance 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
Game.h:
#import <Foundation/Foundation.h>
@interface Game : NSObject
@property (nonatomic, strong) NSNumber *choice;
@property (nonatomic, strong) NSNotificationCenter *ns;
-(void) start;
@end
Game.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
答案 0 :(得分:3)
UIButton没有setImage方法。
您也可以使用相同的现有代码。只需更新以下行
[self.b0 performSelectorOnMainThread:@selector(setImage: ) withObject:[UIImage imageNamed:@"button_x.png"] waitUntilDone:NO];
作为
[self performSelectorOnMainThread:@selector(setImage: ) withObject:[UIImage imageNamed:@"ListDropDown.png"] waitUntilDone:NO];
然后定义方法setImage:
-(void)setImage:(UIImage *)img
{
[self.bo setImage:img forState:UIControlStateNormal];
}
我希望它对你有用
答案 1 :(得分:2)
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];
});
答案 2 :(得分:1)
试试这个,
if (str == 0) {
dispatch_sync(dispatch_get_main_queue(), ^{
[self.b0 setImage:[UIImage imageNamed:@"button_x.png"] forState:UIControlStateNormal];
});
}