Swift: Closure闭包学习

情景: 在一个scrollView上添加n个Button

  • demo01

单纯的无封装无closure


  
        import UIKit

        class ViewController: UIViewController {

        override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        //1.创建UIScrollview
        let scrollView = UIScrollView(frame: CGRect(x: 0, y: 100, width: self.view.bounds.size.width, height: 44))
        scrollView.backgroundColor = UIColor.blueColor()
        
        let width = 80
        //2.创建n多UIButton
        for i  in 0..<15 {
            let btn = UIButton()
            
             //3.设置button属性
            btn.setTitle("标题\(i)", forState: UIControlState.Normal)
            btn.backgroundColor = UIColor.redColor()
            btn.frame = CGRect(x: i*width, y: 0, width: width, height: 44)
           //4.将button添加到UIScrollview上
            scrollView.addSubview(btn)
            
            scrollView.contentSize = CGSize(width: (i+1)*width, height: 44)
        }
        //5.将scrollview添加到view上
        //特点:没有self(self.view) swift推荐能不写self就不写self
        view.addSubview(scrollView)
             }
        }
  • demo02

通过函数进行UIScrollView的创建 - 通过闭包传递按钮的个数、按钮的创建
对入参进行闭包封装,让操作在闭包中完成


import UIKit

class ViewController: UIViewController {
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        
        let sc =  setupScrollView({ () -> Int in
            return 10
        }) { (index) -> UIView in
            
            let width = 80
            
            let btn = UIButton()
            //3.设置button属性
            btn.setTitle("标题\(index)", forState: UIControlState.Normal)
            btn.backgroundColor = UIColor.redColor()
            btn.frame = CGRect(x: index*width, y: 0, width: width, height: 44)
            
            return btn
        }
        view.addSubview(sc)
    }
    
    //要求: 定义一个方法来创建UIScrollView,并且UIScrollView上有多少个按钮必须通过闭包告诉该方法
    //并且如何创建按钮需要通过闭包来创建
    func setupScrollView(btnCount:() -> Int,btnWithIndex:(index:Int) -> UIView) -> UIScrollView {
        //1.创建UIScrollview
        let scrollView = UIScrollView(frame: CGRect(x: 0, y: 100, width: self.view.bounds.size.width, height: 44))
        
        scrollView.backgroundColor = UIColor.blueColor()
        
        let count = btnCount()
        //2.创建n多UIButton
        for i  in 0..

你可能感兴趣的:(Swift: Closure闭包学习)