0

我正在尝试向 UIButton 添加操作,但不断收到异常:

由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“[UIImageView addTarget:action:forControlEvents:]: unrecognized selector sent to instance 0x595fba0”

这是我的代码:

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIImage *myIcon = [UIImage imageNamed:@"Icon_Profile"];
    self.profileButton = (UIButton*)[[UIImageView alloc] initWithImage:myIcon];

    [self.profileButton addTarget:self action:@selector(profileButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

    UIBarButtonItem *buttonItem = [[[UIBarButtonItem alloc] initWithCustomView:profileButton] autorelease];

    NSArray *toolbarItems = [[NSArray alloc] initWithObjects:buttonItem, nil];

    [self setToolbarItems:toolbarItems animated:NO];

    //[toolbarItems release];
    //[profileButton release];
}

然后我在同一个视图控制器中有这个方法:

-(void)profileButtonPressed:(id)sender{

}

在标题中我有

-(IBAction)profileButtonPressed:(id)sender;

这是怎么回事?

4

5 回答 5

4

您正在投射一个不响应UIImageView的。使用或of创建一个实际的按钮并为不同的状态设置图像。UIButtonaddTarget:action:forControlEvents:setBackgroundImage:forState:setImage:forState:UIButton

于 2011-06-30T12:41:03.477 回答
3

为什么要将 UIImageView 转换为按钮。

UIImage *myIcon = [UIImage imageNamed:@"Icon_Profile"];
self.profileButton = [UIButton buttonWithStyle:UIButtonStyleCustom];
[self.profileButton setImage:myIcon forState:UIControlStateNormal];
[self.profileButton addTarget:self action:@selector(profileButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
于 2011-06-30T12:40:18.227 回答
2

这看起来非常错误:

self.profileButton = (UIButton*)[[UIImageView alloc] initWithImage:myIcon];

AUIImageView不是UIButton. 你应该allocinit一个适当的UIButton,然后你可以打电话

[self.profileButton setImage: myIcon forState:UIControlStateNormal];
于 2011-06-30T12:39:55.637 回答
2

首先创建自己的按钮。并在之后添加操作:

UIImage *myIcon = [UIImage imageNamed:@"Icon_Profile"];
UIButton *buttonPlay = [UIButton buttonWithType:UIButtonTypeCustom];
buttonPlay.frame = CGRectMake(0, 0, 20, 20);
[buttonPlay setBackgroundImage:myIcon forState:UIControlStateNormal];
[buttonPlay addTarget:self action:@selector(buttonPlayClick:) forControlEvents:UIControlEventTouchUpInside];

你的选择器应该是这样的

- (void)buttonPlayClick:(UIButton*)sender{
}

现在您可以创建自定义栏项

UIBarButtonItem *buttonItem = [[[UIBarButtonItem alloc] initWithCustomView:buttonPlay] autorelease];
于 2011-06-30T12:41:23.997 回答
2

您不能将UIImageView对象强制转换为UIButton并期望它表现得像UIButton. 由于您打算创建一个UIBarButtonItem,请使用initWithImage:style:target:action:图像对其进行初始化。

UIBarButtonItem *buttonItem = [[[UIBarButtonItem alloc] initWithImage:myIcon style:UIBarButtonItemStylePlain target:self action:@selector(profileButtonPressed:)] autorelease]; 

我认为这是创建 aUIButton并将其分配为自定义视图的更好方法。

于 2011-06-30T12:43:45.300 回答