2013-05-08 88 views
7

我的按鈕如下UIButton的自定義視圖 - addTarget:動作:forControlEvents:不工作

  1. 創建LABEL1
  2. 創建LABEL2
  3. 創建customView(UIView
  4. 添加label1和label2自定義視圖
  5. 創建myCustomButton(UIButton
  6. 在myCustomButton上添加customView

我已經爲custom_View,label1和label2做了userInteractionEnable。

然後加入

[myCustomButton addTarget:self action:@selector(OnButtonClick:) forControlEvents:UIControlEventTouchUpInside]; 

而且

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

但上述功能,甚至當我觸摸按鈕永遠不會被調用。任何解決方案

+0

請把您的相關代碼放在這裏? – 2013-05-08 13:56:10

回答

18

只是你的代碼我的朋友一個小問題,你只需要添加只有一個下面一行到你的代碼,忘了setUserInteractionEnabled:NOUIView它可以讓你按一下按鈕

UILabel *lbl1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)]; 
[lbl1 setText:@"ONe"]; 
UILabel *lbl2 = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, 100, 30)]; 
[lbl2 setText:@"Two"]; 

UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 130)]; 
[view setUserInteractionEnabled:NO]; 

[view addSubview:lbl1]; 
[view addSubview:lbl2]; 

UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom]; 
[btn addSubview:view]; 
[btn setFrame:CGRectMake(0, 0, 200, 130)]; 
[btn addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside]; 

[self.view addSubview:btn]; 

單擊方法

-(void)click 
{ 
    NSLog(@"%s",__FUNCTION__); 
} 
+0

你確定視圖的'setUserInteractionEnabled'應該是NO?我把它設置爲是,然後它工作! – 2014-10-01 18:59:01

+0

是的,因爲button是在'self.view'中添加的,而標籤是在'view'中的,所以如果你禁用它的用戶交互。它沒有任何區別,因爲按鈕和標籤位於不同的容器中。 – 2014-10-02 05:53:18

3

而不是創建customView(UIView的實例),您在CustomViewClicked方法

-(void)customViewClicked:(id)sender 
{ 
    UIControl *senderControl = (UICotrol *)sender; 

    NSLog(@"sender control = %@",senderControl); 
} 

成也addTarget添加customView作爲UIControl的實例的customView,

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
[button setFrame:CGRectMake(10,10,300,300)]; 

UIControl *customView = [[UIControl alloc] initWithFrame:CGRectMake(0,0,300,300)]; 
[customView addTarget:self action:@selector(customViewClicked:) forControlEvents:UIControlEventTouchUpInside]; 

UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(10,10,100,100)]; 
[label1 setText:@"Hello How are you ?"]; 

UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(10,150,100,100)]; 
[label1 setText:@"I am fine Thnank You!"] 

[customView addSubView:lebel1]; 
[customView addSubView:lebel2]; 

現在希望它能幫助你。

+0

感謝您的建議。我得到了解決方案形式的其他答案... – Sagrian 2013-05-09 05:24:01