10

私のボタンは次のとおりです

  1. ラベル1を作成しました
  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
{
}

しかし、ボタンをタッチしても上記の関数は呼び出されません。解決策はありますか?

4

3 に答える 3

27

あなたのコードにはちょっとした問題がありますが、コードに次の行を 1 つだけ追加する必要があります。それを忘れると、ボタンをクリックできるようになります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__);
}
于 2013-05-08T14:22:18.713 に答える
3

customView (UIView のインスタンス) を作成するのではなく、customView を UIControl のインスタンスとして追加し、さらに addTarget を 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];

CustomViewClicked メソッドで

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

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

それがあなたを助けることを願っています。

于 2013-05-08T14:04:47.273 に答える