I want to pass the movie url from my dynamically generated button to MediaPlayer:
[button addTarget:self action:@selector(buttonPressed:) withObject:[speaker
I think the correct method should be :
- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents
UIControl Reference
Where do you get your method from?
I see that your selector has an argument, that argument will be filled by the runtime system. It will send you back the button through that argument.
Your method should look like:
- (void)buttonPressed:(id)BUTTON_HERE {
}
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 UIControl
s [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).
UIButton responds to addTarget:action:forControlEvents: since it inherits from UIControl. But it does not respond to addTarget:action:withObject:forControlEvents:
see reference for the method and for UIButton
You could extend UIButton with a category to implement that method, thought.
I made a solution based in part by the information above. I just set the titleLabel.text to the string I want to pass, and set the titleLabel.hidden = YES
Like this :
UIButton *imageclick = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
imageclick.frame = photoframe;
imageclick.titleLabel.text = [NSString stringWithFormat:@"%@.%@", ti.mediaImage, ti.mediaExtension];
imageclick.titleLabel.hidden = YES;
This way, there is no need for a inheritance or category and there is no memory leak
To add to Tristan's answer, the button can also receive (id)event
in addition to (id)sender
:
- (IBAction) buttonTouchUpInside:(id)sender forEvent:(id)event { .... }
This can be useful if, for example, the button is in a cell in a UITableView and you want to find the indexPath of the button that was touched (although I suppose this can also be found via the sender
element).
I found solution. The call:
-(void) someMethod{
UIButton * but;
but.tag = 1;//some id button that you choice
[but addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
}
And here the method called:
-(void) buttonPressed : (id) sender{
UIButton *clicked = (UIButton *) sender;
NSLog(@"%d",clicked.tag);//Here you know which button has pressed
}