oc与swift混用编程,以及block,闭包的使用方法

##oc与swift混用编程,以及block,闭包的使用方法

@interfaceViewController : UIViewController

@property(nonatomic,copy)BlockValueblockValue;

@end

//oc引用swift需要improt“xxx-swift.h”,这个文件是隐藏的,但是可以import

#import "多态-Swift.h"

@interfaceViewController()

@property(nonatomic,strong)NSString*str ;

@end

@implementationViewController

- (void)viewDidLoad {

    [superviewDidLoad];

 self.view.backgroundColor= [UIColorredColor];


 //oc引用swift类

 ViewControllerMy*my = [[ViewControllerMyalloc]init];

 //swift 通过闭包传值,类似oc的block

    my.backValueBlock= ^(NSString* _Nonnullstr) {

 NSLog(@"swift send a  value ~~~");

    };

    my.sendValue=@"oc传值";

    [self.navigationControllerpushViewController:my animated:YES];


 //oc使用block

 self.blockValue= ^(NSString*str) {

 NSLog(@"%@",str);

    };

 //OC block传值

 if(self.blockValue) {

 self.blockValue(@"OC block传值");

    }

}

@end

//swift 文件里面block写法

importUIKit

typealiasBackValueBlock = (String)->()//声明一个闭包

@objcMembers

classViewControllerMy: UIViewController{

 //从oc 传送过来的值

 varsendValue:String?;

 var  backValueBlock:BackValueBlock?;//把闭包声明成一个属性

 overridefuncviewDidLoad() {

 super.viewDidLoad()


 print("swift view")

 self.view.backgroundColor= UIColor.purple;

 self.navigationItem.title= "swift view";

 print(self.sendValue!)

 letperson = Person.init();

 letblack = blackColor.init();

        person.print(black);

 //创建一个按钮

 letbutton = UIButton.init(type: .custom);

        button.frame= CGRect(x: 0, y: 100, width: 100, height: 100);

        button.backgroundColor= UIColor.red;

        button.setTitle("swift点击", for: .normal);

        button.addTarget(self, action:#selector(buttonClick(btn:)), for: .touchUpInside)

 self.view.addSubview(button);

    }

 //按钮点击事件

 @objcfuncbuttonClick(btn:UIButton){

 print(btn);

 print("点击了button");

 backValueBlock!("swift send a value!!!!");

    }

}

你可能感兴趣的:(oc与swift混用编程,以及block,闭包的使用方法)