需求描述:
在控制器的view上创建一个scrollView,里面添加若干个button
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let sc = UIScrollView()
sc.backgroundColor = UIColor.red
let buttonW = 80
let btnCount = 8
for i in 0..<btnCount
{
let btn = UIButton()
btn.backgroundColor = UIColor.green
btn .setTitle("按钮\(i)", for: UIControlState.normal)
btn.frame = CGRect(x:buttonW*Int(i), y:0, width:buttonW, height:44)
sc.addSubview(btn)
}
sc.frame = CGRect(x:0, y:100, width:view.bounds.size.width, height: 44)
sc.contentSize = CGSize(width:8*buttonW, height:44)
view.addSubview(sc)
}
}
需求描述:用函数实现上面需求,并且创建button个数使用闭包返回
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let sc = creatSubViewsWithCount(buttonCount: { () -> (Int) in
return 8
})
view.addSubview(sc)
}
func creatSubViewsWithCount(buttonCount:() -> (Int)) -> UIScrollView {
let sc = UIScrollView()
sc.backgroundColor = UIColor.red
let buttonW = 80
let btnCount = buttonCount()
for i in 0..<btnCount
{
let btn = UIButton()
btn.backgroundColor = UIColor.green
btn .setTitle("按钮\(i)", for: UIControlState.normal)
btn.frame = CGRect(x:buttonW*Int(i), y:0, width:buttonW, height:44)
sc.addSubview(btn)
}
sc.frame = CGRect(x:0, y:100, width:view.bounds.size.width, height: 44)
sc.contentSize = CGSize(width:8*buttonW, height:44)
return sc
}
}
需求描述:用函数实现上面需求,并且创建子控件个数使用闭包返回,子控件类型是什么,也由另一个闭包决定(即灵活性好,易扩展)
分析:
闭包1返回参数: 返回创建子控件的个数
闭包2传入参数:第几个子控件的索引
闭包2返回参数:第几个新创建的子控件
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let sc = creatSubViewsWithCount(buttonCount: { () -> (Int) in
return 8
}, buttonWithCount: { (index) -> (UIButton) in
let buttonW = 80
let btn = UIButton()
btn.backgroundColor = UIColor.green
btn .setTitle("按钮\(index)", for: UIControlState.normal)
btn.frame = CGRect(x:buttonW*Int(index), y:0, width:buttonW, height:44)
return btn
})
view.addSubview(sc)
}
func creatSubViewsWithCount(buttonCount:() -> (Int),buttonWithCount:(Int) -> (UIButton)) -> UIScrollView {
let sc = UIScrollView()
sc.backgroundColor = UIColor.red
let buttonW = 80
let btnCount = buttonCount()
for i in 0..<btnCount
{
let btn = buttonWithCount(i)
sc.addSubview(btn)
}
sc.frame = CGRect(x:0, y:100, width:view.bounds.size.width, height: 44)
sc.contentSize = CGSize(width:8*buttonW, height:44)
return sc
}
}