iOS中的UIBUTTON行动

时间:2013-10-05 12:56:08

标签: ios uiview uibutton

我有一个带有UIView子类的自定义类,在这里我动态创建了一个按钮。 现在我想为按钮方法设置Action。我像UIviewController一样设置正常。 但它不起作用。

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
    UIButton *but=[UIButton buttonWithType:UIButtonTypeDetailDisclosure];
    but.frame= CGRectMake(200, 15, 15, 15);
    [but setTitle:@"Ok" forState:UIControlStateNormal];
    [but addTarget:self action:@selector(aMethod)
  forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:but];
    // Initialization code
}
return self;
 }

-(void)aMethod
{

    NextEyeViewController *nexteye=[[NextEyeViewController alloc]initWithNibName:@"NextEyeViewController" bundle:nil];
    [self presentViewController:nexteye animated:YES completion:nil];
}

-(void)aMethod是按钮

的方法名称

3 个答案:

答案 0 :(得分:0)

如果要对以编程方式创建的按钮设置操作,则需要执行以下操作:

UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
[button addTarget:self 
           action:@selector(aMethod)
 forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(0.0, 0.0, 160.0, 40.0);
[view addSubview:button];

答案 1 :(得分:0)

创建UIButton:

UIButton *yourButton = [[UIButton alloc] initWithFrame:frameButton];

// Here code to set button properties: color, label...

[yourButton addTarget:self action:@selector(aMethod) forControlEvents:UIControlEventTouchDown];

[self.view addSubview:yourButton];

答案 2 :(得分:-1)

您的方法必须接收操作的发件人:

-(void)aMethod:(id)sender {
   // your code
}

更新: 您还必须使用@selector(aMethod:)而不是@selector(aMethod)来适当地调用您的方法。