[英]How to call swift method from objective c
I have created my custom dialog in swift with xib file Now i want to use that dialog from objective c file I am able to show the dialog but i cannot able to listen click event of button 我已经使用xib文件快速创建了自定义对话框,现在我想使用目标c文件中的该对话框,我能够显示该对话框,但无法监听按钮的单击事件
My Swift code is like 我的Swift代码就像
public class CustomVerificationDialog:UIView,UITextFieldDelegate
{
///Othere stuffs
var onClickRightButton : ((_ text1:String , _ text2:String ) -> Void)? = nil //This method is called when button is clicked
@IBAction func onClickBtnRight(_ sender: Any)
{
if self.onClickRightButton != nil
{
self.onClickRightButton!(editTextOne.text ?? "",editTextTwo.text ?? "")
}
}
}
Now i am able to get the click event in swift like 现在,我能够迅速获得click事件,例如
dialogForVerification.onClickRightButton =
{ (text1:String,text2:String) in
}
But i dont know how to listen it in objective c 但是我不知道如何在目标C中听
CustomVerificationDialog *dialogVerification = [CustomVerificationDialog showCustomDialog];
???
In order to access any swift class and its methods/properties in objective-c file, you need to mark that class/method/property with @objc. 为了访问Objective-C文件中的任何swift类及其方法/属性,您需要使用@objc标记该类/方法/属性。 Then you need to import "TargetName-Swift.h" in your objective-c file in order to access swift code in objective-c file. 然后,您需要在Objective-C文件中导入“ TargetName-Swift.h”,以便访问Objective-C文件中的swift代码。 Here is the code snippet which hopefully solve your problem: 这是希望能解决您问题的代码片段:
Replace your swift class with: 将您的Swift类替换为:
@objc public class CustomVerificationDialog:UIView,UITextFieldDelegate
{
@objc var onClickRightButton : ((_ text1:String , _ text2:String ) -> Void)? = nil //This method is called when button is clicked
@IBAction func onClickBtnRight(_ sender: Any)
{
if self.onClickRightButton != nil
{
self.onClickRightButton!(editTextOne.text ?? "",editTextTwo.text ?? "")
}
}
//other code goes here
}
and In your objective-c file (ie viewController) 并在您的Objective-C文件中(即viewController)
#import "YourTargetName-Swift.h"
...................
................
CustomVerificationDialog *dialogVerification = [CustomVerificationDialog showCustomDialog];
[dialogVerification setOnClickRightButton:^(NSString * _Nonnull text1 , NSString * _Nonnull text2 ) {
}];
// other code here
.................
..................
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.