2013-10-05 30 views
-2

我有一個UIView的子類的自定義類,在這裏我動態地創建了一個按鈕。 現在我想爲按鈕方法設置Action。我設置像UIviewController正常。 但它不工作。iOS中的UIBUTTON ACTION

- (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是按鈕我的方法名

+0

在您自定義的UIView類,你可能需要啓用用戶交互(這是一個屬性,你可以設置爲YES/NO)。 –

+0

我沒有在那裏使用xib來啓用用戶交互 – user2791408

+0

沒關係。如果我沒有弄錯,默認情況下'userInteractionEnabled'對於自定義UIViews被設置爲'NO'--可能出於性能原因。如果你想與視圖上的任何控件(按鈕等)交互,你必須明確地將其設置爲「YES」。 –

回答

-1

你的方法有接收行動的發件人:

​​

更新: 你也必須與@selector(aMethod:)而不是適當調用你的方法@selector(aMethod)

+0

試過但顯示錯誤:( – user2791408

+0

無論如何,您的按鈕將其身份傳遞給您的函數。您可能還有其他錯誤,但這仍然是正確的。 – max

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]; 
+0

是的,我做了這件事,但事情是從一個自定義類(UIview) – user2791408

+0

添加你的代碼 –

+0

添加到請註冊 – user2791408

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];