-2

我有一个带有 UIView 子类的自定义类,在其中我动态创建了一个按钮。现在我想为按钮方法设置动作。我像 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是我的按钮方法名称

4

3 回答 3

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];
于 2013-10-05T13:01:40.573 回答
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];
于 2013-10-05T12:59:29.173 回答
-1

您的方法必须接收操作的发送者:

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

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

于 2013-10-05T12:59:12.293 回答