Call Target Action in Swift

In Swift, how do I execute a Cocoa target-action pattern with a selector defined at runtime?

Specific Features: My code receives UIBarButtonItem, and it needs to invoke the action that this button represents. In Objective-C, this is simple:

UIBarButtonItem* button = ...;
[button.target performSelector: button.action withObject: self];

In Swift is performSelector:not displayed for security reasons by type / memory. I cannot create a Swift closure since I do not know the button.action button at compile time. Any other technology to trigger action?

+4
source share
2 answers

This was answered in the Apple Developer Forums :

UIApplication.sendAction(_:to:from:forEvent:). , Objective-C, , , .

, , :

UIApplication.sharedApplication()
    .sendAction(button.action, to: button.target,
                from: self, forEvent: nil)

, @vladof, UIControl.

+12

, Objective C TestClass, UIBarButtonItem:

- (UIBarButtonItem *)getBarButtonItem
{
    UIBarButtonItem *bar = [[UIBarButtonItem alloc] init];
    bar.target = self;
    bar.action = @selector(help);
    return bar;
}

- (void)help
{
    NSLog(@"Help offered");
}

Swift:

var testClass = TestClass()
var barButtonItem = testClass.getBarButtonItem()
var button: UIButton = UIButton()
button.sendAction(barButtonItem.action, to: barButtonItem.target, forEvent: nil)

:

2014-07-06 23: 49: 49.942 TestApp [53986: 2552835]

, UIControl UIButton.

+3

Source: https://habr.com/ru/post/1547351/


All Articles