0

我正在设置 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错误。关于我做错了什么有什么想法吗?

4

1 回答 1

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"

于 2012-08-11T22:12:05.963 回答