Cocos与IOS交互
js调用oc方法
项目方法:
if (cc.sys.isNative && cc.sys.os == cc.sys.OS_IOS) {
let ret = jsb.reflection.callStaticMethod("AppController","showAd:title:","title","message");
cc.log(ret)//打印输出:hehe
this.label.string = "点击按钮了:" + ret;
}
注意:
该方法调用的是AppController类的showAd()方法,传递的参数是(title, message);
原生修改:
AppController.h
#import <UIKit/UIKit.h>
@class RootViewController;
@interface AppController : NSObject <UIApplicationDelegate>
{
}
+(NSString *)showAd:(NSString *)str title:(NSString *)tit;
@property(nonatomic, readonly) RootViewController* viewController;
@end
AppController.m
+(NSString *)showAd:(NSString *)str title:(NSString *)tit{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:tit message:str delegate:nil cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
[alertView show];
return @"hehe";
}
测试:
展示图
oc调用js方法
1.在window中创建全局变量和方法
window.label = null;
window.testMethod = (str)=>{
cc.log('window.testMethod' , str);
// if(window.label){
window.label.string = "回调函数:" + str;
// }
return 'abcd';
}
2.在oc原生中调用相应的方法
+(NSString *)showAd:(NSString *)str title:(NSString *)tit{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:tit message:str delegate:nil cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
[alertView show];
// call the js function
// 声明一个字符串
std::string strRet = "haha";
// 获取cocos方法字符串
std::string jsCallStr = cocos2d::StringUtils::format("testMethod(\"%s\");", strRet.c_str());
// 声明一个返回值
se::Value *ret = new se::Value();
// 执行这个方法
se::ScriptEngine::getInstance()->evalString(jsCallStr.c_str() , -1 , ret);
// Log输出返回值
NSLog(@"jsCallStr rtn = %s", ret->toString().c_str());
//////////////////
return @"hehe";
}
3.与cocos界面交互
创建相应的方法,节点、对象的全局引用,然后通过上述方法调用
评论