简体   繁体   中英

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

My Swift code is like

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

dialogForVerification.onClickRightButton =
            { (text1:String,text2:String) in
                }

But i dont know how to listen it in objective c

CustomVerificationDialog *dialogVerification =  [CustomVerificationDialog showCustomDialog];
???

You can try

[dialogVerification setOnClickRightButton:^(NSString * _Nonnull text1 , NSString * _Nonnull text2 ) {

}];

Here is a Demo

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. Then you need to import "TargetName-Swift.h" in your objective-c file in order to access swift code in objective-c file. Here is the code snippet which hopefully solve your problem:

Replace your swift class with:

    @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)

#import "YourTargetName-Swift.h"

...................
................
CustomVerificationDialog *dialogVerification =  [CustomVerificationDialog showCustomDialog];
[dialogVerification setOnClickRightButton:^(NSString * _Nonnull text1 , NSString * _Nonnull text2 ) {

}];
// other code here
.................
..................

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM