2

私はいくつかのラベルとボタンを作成しているクラスCustomView( UIViewxib ファイルなしのサブクラス) を持っています。このクラスを別のクラスで使用しUIViewControllerて、それらのラベルとボタンを追加したかったのです。カスタムビューを使用してviewControllerにラベルとボタンを追加できますが、ボタン(カスタムビューにある)にアクションまたはイベントを追加すると機能しません。ボタンのアクションを追加するにはどうすればよいか教えてください。

//ViewController code

CustomView *slider=[[CustomView alloc]init];
[self.view addSubview:slider];

//CustomView code


toggleButton = [UIButton buttonWithType:UIButtonTypeCustom];
[toggleButton setTitle:@"" forState:UIControlStateNormal];
toggleButton.userInteractionEnabled=YES;

// add drag listener
[toggleButton addTarget:self action:@selector(wasDragged:withEvent:)
       forControlEvents:UIControlEventTouchDragInside];



// center and size
toggleButton.frame = CGRectMake(frame.origin.x, frame.origin.y, width, frame.size.height);

toggleButton.backgroundColor=[UIColor colorWithRed:0.1 green:0.1 blue:0.0 alpha:0.1];
[toggleButton.layer setBorderWidth:4.0];
[toggleButton.layer setBorderColor:[[UIColor lightGrayColor] CGColor]];
toggleButton.layer.cornerRadius=4.0;
[toggleButton setTitleColor:[UIColor colorWithRed:0.3 green:0.1 blue:0.4 alpha:1.0] forState:UIControlStateNormal];

// add it, centered
[self addSubview:toggleButton];


  - (void)wasDragged:(UIButton *)button withEvent:(UIEvent *)event 
  {
   NSLog(@"inside drag");
  }
4

4 に答える 4

0

selfアクションはターゲットを追加しましたwasDragged:withEvent。これが機能するためには(カスタムビューで宣言されていると仮定してwasDragged:withEvent)、コードを次のように書き直す必要があります。

[toggleButton addTarget:slider action:@selector(wasDragged:withEvent:)
       forControlEvents:UIControlEventTouchDragInside];
于 2013-02-21T07:21:26.757 に答える
0

この行を置き換えます

[toggleButton addTarget:self action:@selector(wasDragged:withEvent:)
       forControlEvents:UIControlEventTouchDragInside];

これとともに

[toggleButton addTarget:self action:@selector(wasDragged:withEvent:)
       forControlEvents:UIControlEventTouchUpInside];

これがうまくいくことを願っています

于 2013-02-21T06:51:49.103 に答える
0

メソッド wasDragged:withEvent はどこに配置しましたか? CustomView コードでは、ボタン ターゲットを customview である self に設定しているためです。したがって、ボタン TouchDragInside イベントは、viewController ではなく customview に送信されます。ViewController に wasDragged:withEvent を入れても動かない

于 2013-02-21T06:53:24.973 に答える