swift中的閉包跟OC中的Block原理相似
本文用一個小Demo來展示具體用法
首先自定義了一個view官册,然后定義閉包,最后在viewcontroller中創(chuàng)建view并使用閉包傳值
自定義view的代碼:
import UIKit
//typealias IndexBlock = (index:NSInteger)->Void
class CustomView: UIView {
var IndexBlock:((index:NSInteger)->()) = {_ in }
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
// var callBack:IndexBlock!
var button1:UIButton?
var button2:UIButton?
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupUI() {
self.button1 = UIButton.init(type: .Custom)
self.button1?.backgroundColor = UIColor.redColor()
self.button1?.frame = CGRectMake(0, 65, 60, 30)
self.button1?.tag = 1
self.button1?.addTarget(self, action: #selector(buttonClick), forControlEvents: .TouchUpInside)
self.addSubview(self.button1!)
self.button2 = UIButton.init(type: .Custom)
self.button2?.backgroundColor = UIColor.blueColor()
self.button2?.frame = CGRectMake(0, 100, 60, 30)
self.button2?.tag = 2
self.button2?.addTarget(self, action: #selector(buttonClick), forControlEvents: .TouchUpInside)
self.addSubview(self.button2!)
}
func buttonClick(sender:UIButton){
// self.callBack!(index: sender.tag)
self.IndexBlock(index: sender.tag)
}
}
viewcontroller中的代碼:
import UIKit
class ViewController: UIViewController {
var cv:CustomView?
var label:UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
configViews()
}
func configViews() {
self.title = "首頁"
self.view.backgroundColor = UIColor.whiteColor()
setupData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController {
func setupData(){
self.cv = CustomView.init(frame: CGRectMake(10, 10, 300, 300))
self.cv!.backgroundColor = UIColor.yellowColor()
self.view.addSubview(self.cv!)
self.label = UILabel.init(frame: CGRectMake(10, 360, 200, 30))
self.label.backgroundColor = UIColor.redColor()
self.view.addSubview(self.label)
/*
self.cv?.callBack = {(index:NSInteger)->() in
self.label.text = String(index)
}
*/
self.cv?.IndexBlock = {(index:NSInteger)->() in
self.label.text = String(index)
}
}
}
代碼中閉包用了兩種寫法血巍,一種是常規(guī)寫法践付,一種使用了typealias
不過我注釋掉了其中一種寫法,兩種實現(xiàn)效果是一樣的吃挑,可以根據(jù)自己的習(xí)慣去選擇哪種寫法