ReactiveCocoa在swift情况下使用宏

在swift的环境下,配置RAC和RACObserve宏需要另外添加文件,如下:

import ReactiveCocoa
public struct RAC  {
    var target : NSObject!
    var keyPath : String!
var nilValue : AnyObject!

init(_ target: NSObject!, _ keyPath: String, nilValue: AnyObject? = nil) {
    self.target = target
    self.keyPath = keyPath
    self.nilValue = nilValue
 }

func assignSignal(signal : RACSignal) {
    signal.setKeyPath(self.keyPath, onObject: self.target, nilValue: self.nilValue)
  }
 }

public func RACObserve(target: NSObject!, keyPath: NSString) -> RACSignal  {
   return target.rac_valuesForKeyPath(keyPath as String, observer: target)
}

public func <= (rac:RAC, signal:RACSignal){
   rac.assignSignal(signal)
} 

public func >=( signal:RACSignal, rac:RAC){
 rac.assignSignal(signal)
}

在学习swift导入RAC的过程中,由于宏在OC项目中非常好用,但是宏在swift中不好使,需要额外导入文件才能正常使用.
下面举了一个textFiled输入文字时,改变下面的那个label内容:

  import UIKit
  import SnapKit
  import ReactiveCocoa
  //import ReactiveCocoa.RACEXTScope

  func == (Str1:String,Str:String) ->Bool{      
      return true
  }

  class ViewController: UIViewController {


override func viewDidLoad() {
    super.viewDidLoad()
    view.addSubview(textFiled)
    view.addSubview(label)
    
    textFiled.snp_makeConstraints { (make) in
        make.center.equalTo(self.view)
        make.width.equalTo(100)
        make.height.equalTo(30)
    }
    
    label.snp_makeConstraints { (make) in
        make.top.equalTo(textFiled).offset(20)
        make.centerX.equalTo(textFiled)
        make.width.equalTo(100)
        make.height.equalTo(30)
    }
    
    let str1 = "1"
    let str2 = "2"
    let bool = str1==str2
    print(bool)
    RAC(label,"text") <= textFiled.rac_textSignal()

  

    RACObserve(label, keyPath: "center") .subscribeNext { (x) in
        print("移动的距离为:\(x)" 
    }

}

override func touchesBegan(touches: Set, withEvent event: UIEvent?) {
  //点击屏幕label向下移动
    label.snp_remakeConstraints { (make) in
        make.top.equalTo(textFiled).offset( number * 20)
        make.centerX.equalTo(textFiled)
        make.width.equalTo(100)
        make.height.equalTo(30)
    }
    
    number += 1
}

private lazy var textFiled : UITextField={
    let textFiled = UITextField()
    textFiled.placeholder = "请输入文字"
    return textFiled
}()

private lazy var label : UILabel={
    let label = UILabel()
    label.text = "我是占位文字,textFiled改变时我也会改变"
    label.font = UIFont.systemFontOfSize(16)
    
    return label
  }()

}
  • 其中textFiled绑定label的核心代码就是:

     // 只要文本框文字改变,就会修改label的文字
     RAC(label,"text") <= textFiled.rac_textSignal()
    

一句话就可以实现绑定textFiled变化时,label也跟着变化

  • 其中点击屏幕label往下移动的核心代码是:

     RACObserve(label, keyPath: "center") .subscribeNext { (x) in
         print("移动的距离为:\(x)" 
     }
    

RACObserve宏代码会让其返回一个Signal,我们使用订阅的时候,即可像KVO一样绑定信息,监控对象某个属性的变化.

你可能感兴趣的:(ReactiveCocoa在swift情况下使用宏)