Swift学习

swift-基础-闭包

2016-08-15  本文已影响46人  埃林的奶酪
// 定义一个闭包属性(类似OC的strong属性)
// 返回值为空,那么可以用()代替
var finished: (() -> ())?
//类型的格式:(形参列表) -> 返回值类型
//值的格式:
{
    (形参列表) -> 返回值类型
    in // in的作用是分隔需要执行的代码
    需要执行的代码
}
self.finished = {
    () -> ()
    in
    print("我被调用了")
}
// 调用,此处加叹号是因为必须保证闭包中有值才能调用(类似OC中block也必须先判断block是否有值)
self.finished!()

具体使用

dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in

    print("执行了耗时操作")

    print(NSThread.currentThread())

    

    dispatch_async(dispatch_get_main_queue(), { () -> Void in

        print("更新了UI")

        print(NSThread.currentThread())

    })

}
func creatScrollView(btnCount: ()-> Int, btnWithIndex: (index:Int) ->UIView) -> UIScrollView

    {

        let sc = UIScrollView(frame: CGRect(x: 0, y: 100, width: 375, height: 44))

        sc.backgroundColor = UIColor.redColor()

        let count = btnCount()

        for i in 0..<count

        { // subView由调用者决定,而index由这里决定并传给调用者

            let subView = btnWithIndex(index: i)

            sc.addSubview(subView)

            sc.contentSize = CGSize(width: CGFloat(count) * subView.bounds.width, height: 44)

        }

        

        return sc

    }
// 调用
let sc = creatScrollView({ () -> Int in

            return 15

            }) { (index) -> UIView in

                let width = 80

                let btn = UIButton()

                btn.backgroundColor = UIColor.greenColor()

                btn.setTitle("标题\(index)", forState: UIControlState.Normal)

                btn.frame = CGRect(x: index * width, y: 0, width: width, height: 44)

                return btn

        }

        view.addSubview(sc)

闭包的简写

func loadData(finished: ()->())

{

    print("执行了耗时操作")

    // 调用闭包

    finished()

}

loadData ({ () -> () in

    print("耗时操作执行完毕")

})
loadData {
    print("耗时操作执行完毕")
}

闭包的循环引用

weak var weakSelf = self
loadData ({ () -> () in

    print("耗时操作执行完毕")
    weakSelf!.view.backgroundColor = UIColor.redColor

})
loadData ({ [weak self] () -> () in

    print("耗时操作执行完毕")
    self!.view.backgroundColor = UIColor.redColor

})
loadData ({ [unowned self] () -> () in

    print("耗时操作执行完毕")
    self.view.backgroundColor = UIColor.redColor

})
上一篇 下一篇

猜你喜欢

热点阅读