Passing parameters on button action:@selector

前端 未结 11 1330
生来不讨喜
生来不讨喜 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 17:48

    tl;dr: Use Blocks

    For Obj-C, for example, there's a CocoaPod SHControlBlocks, whose usage would be:

    [self.btnFirst SH_addControlEvents:UIControlEventTouchDown withBlock:^(UIControl *sender) {
        [weakSelf performSegueWithIdentifier:@"second" sender:nil];
        NSLog(@"first");
      }];
    

    For Swift, I love the pod Actions, which allows blocks for UIControls [1]:

    // UIControl
    let button = UIButton()
    button.add(event: .touchUpInside) {
        print("Button tapped")
        playMusic(from: speakers_mp4, withSongAtPosition: indexPath.row)
    }
    

    Not that anyone is reading a 3-year old thread. ::crickets::

    [1] And UIView, UITextField, UIGestureRecognizer, UIBarButtonItem, Timer (formally NSTimer), and NotificationCenter (formally NSNotificationCenter).

提交回复
热议问题