Recently, when answering the stackoverflow question, we found that the javasmselector method was removed in swift, and Apple commented that this method was removed because it was not safe:
NOTEThe performSelector: method and related selector-invoking methods are not imported in Swift because they are inherently unsafe.
If you call this method in swift, an error occurs during compilation:
‘performSelector‘ is unavailable: ‘performSelector‘ methods are unavailable
After repeated attempts, I found that uicontrol can be used.:
func sendAction(_ action: Selector, to target: AnyObject!, forEvent event: UIEvent!)
The following is a Demo code:
import UIKitclass ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. var control:UIControl = UIControl() control.sendAction(Selector("greetings"), to: self, forEvent: nil) } func greetings() { println("greetings world") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. }}
Log output:
greetings world
If swift calls the Target and Action of the objective-C class, you can refer to the following example. Assume that testclass is the objective-C class, And getbarbuttonitem returns uibarbuttonitem:
#import "TestClass.h"@implementation TestClass- (UIBarButtonItem *)getBarButtonItem{ UIBarButtonItem *bar = [[UIBarButtonItem alloc] init]; bar.target = self; bar.action = @selector(help); return bar;}- (void)help{ NSLog(@"Help offered");}@end
In swift, you can use the following code to execute the help method:
import UIKitclass ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. var testClass = TestClass() var button: UIButton = UIButton() var barButtonItem = testClass.getBarButtonItem() button.sendAction(barButtonItem.action, to: barButtonItem.target, forEvent: nil) } }
Log output:
2014-07-06 23:49:49.942 TestApp [53986:2552835] Help offered
I am using xcode 6 beta2. I hope this method will not be removed recently.
|
Yang Zhou Source: http://yangzhou1030.cnblogs.com The copyright of this article is shared by the author and the blog Park. It is not allowed to be reproduced without the consent of the author. The author reserves the right to pursue legal liability. Please provide the original article connection clearly on the article page, and the author reserves the right to pursue legal liability. |