Passing parameters on button action:@selector

前端 未结 11 1313
生来不讨喜
生来不讨喜 2020-11-27 17:29

I want to pass the movie url from my dynamically generated button to MediaPlayer:

[button addTarget:self action:@selector(buttonPressed:) withObject:[speaker         


        
11条回答
  •  北海茫月
    2020-11-27 18:12

    Edit. Found a neater way!

    One argument that the button can receive is (id)sender. This means you can create a new button, inheriting from UIButton, that allows you to store the other intended arguments. Hopefully these two snippets illustrate what to do.

      myOwnbutton.argOne = someValue
      [myOwnbutton addTarget:self action:@selector(buttonTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
    

    and

    - (IBAction) buttonTouchUpInside:(id)sender {
      MyOwnButton *buttonClicked = (MyOwnButton *)sender; 
      //do as you please with buttonClicked.argOne
    }
    

    This was my original suggestion.

    There is a way to achieve the same result, but it's not pretty. Suppose you want to add a parameter to your navigate method. The code below will not allow you to pass that parameter to navigate.

    [button addTarget:self action:@selector(navigate) forControlEvents:UIControlEventTouchUpInside];
    

    To get around this you can move the navigate method to a class of it's own and set the "parameters" as attributes of that class...

    NavigationAid *navAid = [[NavigationAid alloc] init];
    navAid.firstParam = someVariableOne
    navAid.secondParam = someVariableTwo
    [button addTarget:navAid action:@selector(navigate) forControlEvents:UIControlEventTouchUpInside];
    

    Of course you can keep the navigate method in the original class and have it called by navAid, as long as it knows where to find it.

    NavigationAid *navAid = [[NavigationAid alloc] init];
    navAid.whereToCallNavigate = self
    navAid.firstParam = someVariableOne
    navAid.secondParam = someVariableTwo
    [button addTarget:navAid action:@selector(navigate) forControlEvents:UIControlEventTouchUpInside];
    

    Like I said, it's not pretty, but it worked for me and I haven't found anyone suggesting any other working solution.

提交回复
热议问题