iOS中使用JSPatch框架使Objective-C与JavaScript代码交互

2020-01-15 15:53:45王振洲


/*
classDeclaration:要添加或者重写方法的类名 字符串 如果此类不存在 则会创建新的类
instanceMethods:要添加或者重写的实例方法 {}
classMethods:要添加或者重写的类方法 {}
*/
defineClass(classDeclaration, instanceMethods, classMethods)

示例如下:


defineClass('ViewController', {
      // replace the -genView method
        newFunc: function() {
          //编写实例方法
          self.view().setBackgroundColor(UIColor.redColor())
        }
  
      },{

        myLoad:function(){
          //编写类方法
        }

      }
      )

如果在重写了类中的方法后要调用原方法,需要使用ORIG前缀,示例如下:


defineClass('ViewController', {
      // replace the -genView method
        viewDidLoad: function() {
          //编写实例方法
          self.ORIGviewDidLoad()
        }
  
      }
      )

对于Objective-C中super关键字调用的方法,在JavaScript中可以使用self.super()来调用,例如:


defineClass('ViewController', {
      // replace the -genView method
        viewDidLoad: function() {
          //编写实例方法
          self.super().viewDidLoad()
        }
  
      }
      )

同样JSPatch也可以为类添加临时属性,用于在方法间参数传递,使用set_Prop_forKey()来添加属性,使用getProp()来获取属性,注意,JSPatch添加的属性不能使用Objective-C的setter与getter方法访问,如下:


defineClass('ViewController', {
      // replace the -genView method
        viewDidLoad: function() {
          //编写实例方法
          self.super().viewDidLoad()
          self.setProp_forKey("JSPatch", "data")
        },
        touchesBegan_withEvent(id,touch){
          self.getProp("data")
          self.view().setBackgroundColor(UIColor.redColor())
        }
  
      }
      )

关于为类添加协议的遵守,和Objective-C中遵守协议的方式一致,如下:


defineClass("ViewController2: UIViewController <UIAlertViewDelegate>", {
      viewDidAppear: function(animated) {
      var alertView = require('UIAlertView')
      .alloc()
      .initWithTitle_message_delegate_cancelButtonTitle_otherButtonTitles(
                                        "Alert",
                                        "content",
                                        self,
                                        "OK",
                                        null
                                        )
      alertView.show()
      },
      alertView_clickedButtonAtIndex:function(alertView, buttonIndex) {
      console.log('clicked index ' + buttonIndex)
      }
      })