for i in 0 ..< 5 {
let button = UIButton()
view.addSubview(button)
button.backgroundColor = .green
button.snp.makeConstraints { (make) in
make.left.equalToSuperview()
make.width.height.equalTo(50)
make.top.equalTo(i*60)
}
button.rx.tap.subscribe(onNext: {
print(i)
}).disposed(by: rx.disposeBag)
}
点击button输出全部为4,这和OC不一样。在OC Block中对局部自动变量的捕获方式默认为值捕获,而在swift中默认为指针捕获。若要将闭包捕获方式改为值捕获,参考如下:
button.rx.tap.subscribe(onNext: { [i] in
print(i)
}).disposed(by: rx.disposeBag)
输出结果为0,1,2,3,4。