开发者

UIButton : managing dynamic creation and touch events

开发者 https://www.devze.com 2023-01-04 03:39 出处:网络
I\'m currently dynamically creating UIButton objects in my view. I have an NSMutableArray containing information about them (id - label).

I'm currently dynamically creating UIButton objects in my view.

I have an NSMutableArray containing information about them (id - label).

I then create my view objects by doing a for iteration on my MutableArray.

I'm trying to use this code on my buttons to catch touche events :

[myButton addTarget:self action:@selector(selectedButton:) forControlEvents:UIControlEventTo开发者_JAVA技巧uchUpInside];

My selectedButton method is called with success, but I don't have any idea on knowing with button were touched.

I tried to do this :

-(void)selectedButton:(id)sender {...}

But don't know what to do with the sender object.

Thanks in advance for your help !


At the top of your .m file, put something like this:

enum {
    kButtonOne,
    kButtonTwo  
};

When you're creating your buttons, do this

myButton.tag = kButtonOne;

Then in your selected button method, do this:

-(void)selectedButton:(id)sender {
  switch (sender.tag) {
    case kButtonOne:
      // do something here
      break;
    case kButtonTwo:
      // do something else here
      break;
  }
}


Set mybutton.tag to something, and then check for that tag in selectedButton:sender.


-(void)viewDidLoad{

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];

button.frame = CGRectMake(80.0, 210.0, 40.0, 30.0);

button.tag=1;

[button addTarget:self 
           action:@selector(aMethod:)
 forControlEvents:UIControlEventTouchDown];

[button setTitle:@"raaz" forState:UIControlStateNormal];

[self.view addSubview:button];

}

-(IBAction)aMethod:(id)sender{

UIButton *btn=(UIButton *)sender;

NSLog(@"I have currently Pressed button=%d",btn.tag);


}
0

精彩评论

暂无评论...
验证码 换一张
取 消