Swift学习--闭包的简单使用(三)

时间:2023-12-05 12:12:08

一.Swift中闭包的简单使用

 override func viewDidLoad() {
super.viewDidLoad() /**
闭包和OC中的Block非常相似
OC中的block类似于匿名函数
闭包是用来定义函数
作用:Block是用于保存一段点,在需要的时候执行
闭包也是用于保存一段点,在需要的时候执行做一个耗时操作
*/
/**
闭包的基本格式:
{
(形参列表)->()
in
需要执行的代码
}
*/
/**
* 闭包的几种格式:
1.将闭包通过实参传递给函数
2.如果闭包是函数的最后一个参数,那么闭包可以写在函数()的后面
3.如果函数只接收一个参数,并且这个参数是闭包,那么()可以省略
*/
loadData (, finished: {() -> () in
print("被回调了")
})
loadData (){ () -> () in
print("被回调了")
}
say { () -> () in
print("hello")
}
/**
闭包的简写:
如果闭包没有参数也没有返回值,那么,in之前的东西都可以删除,包括in
*/
loadData() {
print("hahfhahf ")
}
} func say(finish: ()->())
{ } func loadData(num: Int, finished: ()->())
{
print("执行耗时操作")
//回调通知调用者
finished()
} override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
//Swift中dispatch_async回调的是一个闭包
dispatch_async(dispatch_get_global_queue(, )) { () -> Void in
print(NSThread.currentThread())
print("执行耗时操作")
dispatch_async(dispatch_get_main_queue(), { () -> Void in
print(NSThread.currentThread())
print("回到主线程更新UI")
})
}
}

二.使用闭包 创建一个UIScrollView

 override func viewDidLoad() {
super.viewDidLoad()
let sc = createScrollView({ () -> Int in
return
}) { (index) -> UIView in
let width =
let btn = UIButton()
//3.设置按钮的属性
btn.backgroundColor = UIColor.greenColor()
btn.setTitle("标题\(index)", forState: UIControlState.Normal)
btn.frame = CGRect(x: index * width, y: , width: width, height: )
//4.返回建好的控件
return btn }
view.addSubview(sc)
}
//定义一个方法来创建UIScrollview,
//1.并且UIScrollview上有多少个按钮必须通过闭包告诉该方法
//2.按钮也通过闭包来创建
func createScrollView(btnCount: ()-> Int, btnWithIndex: (index:Int) ->UIView) -> UIScrollView
{
// 1.创建UIScrollview
let sc = UIScrollView(frame: CGRect(x: , y: , width: , height: ))
sc.backgroundColor = UIColor.redColor() // let width = 80
let count = btnCount()
//添加多个按钮
for i in ..<count
{
// let btn = UIButton()
// //设置按钮的属性
// btn.backgroundColor = UIColor.greenColor()
// btn.setTitle("标题\(i)", forState: UIControlState.Normal)
// btn.frame = CGRect(x: i * width, y: 0, width: width, height: 44)
// //将按钮添加
// sc.addSubview(btn)
let subView = btnWithIndex(index: i)
sc.addSubview(subView)
sc.contentSize = CGSize(width: CGFloat(count) * subView.bounds.width, height: )
} return sc
}

Swift学习--闭包的简单使用(三)