以编程方式将IBAction添加到UIButton

时间:2011-06-30 12:35:14

标签: ios objective-c ibaction

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

  

由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'[UIImageView addTarget:action:forControlEvents:]:无法识别的选择器发送到实例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];
}

然后我在同一个View控制器中使用此方法:

-(void)profileButtonPressed:(id)sender{

}

在标题中我有

-(IBAction)profileButtonPressed:(id)sender;

发生了什么事?

5 个答案:

答案 0 :(得分:4)

您正在向UIImageView投射UIButton而不回复addTarget:action:forControlEvents:。使用setBackgroundImage:forState:的{​​{1}}或setImage:forState:创建实际按钮并设置不同状态的图像。

答案 1 :(得分: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];

答案 2 :(得分:2)

这看起来非常错误:

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

UIImageView不是UIButton。您应allocinit使用正确的UIButton,然后拨打电话

[self.profileButton setImage: myIcon forState:UIControlStateNormal];

答案 3 :(得分: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];

答案 4 :(得分:2)

您无法将UIImageView个对象投射到UIButton,并期望它的行为类似于UIButton。由于您打算创建UIBarButtonItem,请使用initWithImage:style:target:action:使用图片初始化它。

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

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

相关问题