简体   繁体   中英

Can I assign two buttons to a same action or outlet in Xcode 7?

I have created a user interface for iPhones in the 'w Compact h Any' tab in the interface builder. I then decided to make a different interface for the iPad version of the app, in 'w Regular h Regular', but when dragging the buttons and labels to the actions and outlets in my ViewController.h file, they replace the buttons and labels in the other interface.

Is there any way I can preserve both at the same time?

You can click+drag from the IBAction method's little connector circle straight to another control in your storyboard, even if it's already been connected to one (and actually I think you can drag from the storyboard object to the IBAction too).

Just keep in mind if you're using different classes, you'll probably want to use id and check the class name before you do stuff with it:

- (IBAction)buttonPressed:(id)sender {
    if ([sender isKindOfClass:[UIButton class]]) {
        //
    }
}

To verify that it's connected to both, click the method circle:

If you're writing Swift in Xcode 7 or 8, the method created will use the Any type; you'll need to change it to UIButton in order for this to work:

@IBAction func buttonPressed(sender: UIButton) {
    //                                  ^
}

You can assign same action for two button by giving tag to each button but you cant give same outlet for two buttons.

For example :

suppose you have two buttons like as below:

  UIButton *btn1 = [[UIButton alloc]initWithFrame:(YourFrame)];
    btn1.tag=1;
   [btn1 addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
   [self.view addSubview:btn1];

  UIButton *btn2 = [[UIButton alloc]initWithFrame:(YourFrame)]; 
   btn2.tag=2;
  [btn2 addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
  [self.view addSubview:btn2];

then

- (IBAction)buttonTapped:(UIButton *)sender
{
    if ((sender.tag=1))
    {
      // btn1 clicked, do something for btn1 click action here...
    }
    else if ((sender.tag=2))
    {
      //btn2 clicked, do something for btn2 clik action here...
    }
}

this is for programatically buttons but if you are doing it using storyboard then same procedure is for that .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM