我正在设置UINavigationBar并且按钮有问题。当我这样做时:
-(void)addLeftButton:(NSString *)titl
{
UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithTitle:titl style:UIBarButtonItemStyleBordered target:self action:@selector(haikuInstructions)];
self.titleOfNavItem.leftBarButtonItem = button;
}
然后一切都很好。但如果我这样做:
-(void)addLeftButton:(NSString *)titl callingMethod:(NSString *)method
{
UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithTitle:titl style:UIBarButtonItemStyleBordered target:self action:@selector(method)];
self.titleOfNavItem.leftBarButtonItem = button;
}
并以另一种方法调用该方法:
[self addLeftButton:@"Instructions" callingMethod:@"haikuInstructions"];
我收到unrecognized selector
错误。关于我做错了什么的想法?
答案 0 :(得分:3)
您应该使用NSSelectorFromString(NSString *aSelectorName)
:
UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithTitle:titl style:UIBarButtonItemStyleBordered target:self action:NSSelectorFromString(method)];
修改强>
详细说明,@selector
指令将在字面上对括号内的名称进行处理。更重要的是,它不会检查该方法是否真的存在。这意味着,如果您使用@selector(method)
并且还有变量NSString *method = @"haikuInstructions"
,则不会指向名为"haikuInstructions"
的选择器,而是指向名为"method"
的选择器。