使用闭包的小案例(一)传参和返回值

需求描述:

在控制器的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..

需求描述:用函数实现上面需求,并且创建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..

需求描述:用函数实现上面需求,并且创建子控件个数使用闭包返回,子控件类型是什么,也由另一个闭包决定(即灵活性好,易扩展)

分析:
闭包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..

你可能感兴趣的:(使用闭包的小案例(一)传参和返回值)