Swift语法--12-2闭包的参数和返回值
先看一个普通的例子:在一个scrollView中添加15个button
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 1.创建UIScrollview
let scV = UIScrollView(frame: CGRect(x: 0, y: 200, width: UIScreen.mainScreen().bounds.width, height: 50))
scV.backgroundColor = UIColor.redColor()
// 2.通过循环创建15个按钮
let count = 15
let width: CGFloat = 80
let height = scV.bounds.height
for i in 0..<count
{
let btn = UIButton()
btn.frame = CGRect(x: CGFloat(i) * width, y: 0, width: width, height: height)
btn.backgroundColor = UIColor.grayColor()
btn.setTitle("第\(i)", forState: UIControlState.Normal)
//将button添加到scrollView中
scV.addSubview(btn)
}
//设置scrollView的contentSize
scV.contentSize = CGSize(width: CGFloat(count) * width, height: height)
//将scrollView添加到view上去
view.addSubview(scV)
}
}
需求:
- 要求创建UIScrollview以及按钮通过一个方法来创建
- 并且按钮的个数必须通过闭包来指定
- 并且如何创建按钮也必须通过闭包来指定(UIScrollview上面添加什么控件通过闭包传递)
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let scrollV = creatScrollV({ () -> Int in
return 20
}) { () -> UIButton in
let btn = UIButton()
btn.backgroundColor = UIColor.grayColor()
return btn
}
view.addSubview(scrollV)
}
func creatScrollV (getCount:()->Int, getSingleButton: ()->UIButton)->UIScrollView{
let scrollV = UIScrollView()
scrollV.backgroundColor = UIColor.redColor()
scrollV.frame = CGRect(x: 0, y: 200, width: UIScreen.mainScreen().bounds.width, height: 80)
//添加按钮
let count = getCount() ////闭包作为参数传过来
let height = scrollV.bounds.height
let width:CGFloat = 70
for i in 0..<count{
//闭包作为参数传过来
let btn = getSingleButton()
btn.setTitle("\(i)", forState: UIControlState.Normal)
btn.frame = CGRect(x: CGFloat(i) * width, y: 0, width: width, height: height)
scrollV.addSubview(btn)
}
scrollV.contentSize = CGSize(width: width * CGFloat(count), height: height)
return scrollV
}
}
网友评论