swift学习之闭包

闭包和oc中的block非常相似,OC中的block非常像匿名的函数,闭包是用来定义函数(方法的)。作用:
1. block是用来保存一段代码,在需要的时候执行。复习block
2. 闭包也是用来保存一段代码,在需要的时候执行

闭包的基本格式:

in的含义是区分形参返回值和执行的代码,可以省略
无参数的闭包形式

    {
        () -> ()
        in
        //执行的代码
    }

带有参数的闭包形式:

 {
        (形参:数据类型,形参:数据类型) -> 返回值
        in
        //执行的代码
  }
返回值为空的时候用“()”
block和闭包的对比:

block代码:

dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSLog(@"当前的线程:%@",[NSThread currentThread]);
        NSLog(@"执行超时的任务");
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"当前的线程:%@",[NSThread currentThread]);
            NSLog(@"主线称更新UI");
        });
    });

swift的闭包代码:

dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
            print("执行超时任务")
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                print("主线程跟新UI")
            })
        }
用闭包实现一个小例子,在UIScrollerView上添加若干UIview的例子,中间实现了两个闭包,进行传参。
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        //获取scrollView
        let sv = creatScrollerView({ () -> Int in
            //创建多少个UIView
            return 10

            }) { (index) -> UIView in
                //创建View
                let btn = UIButton()
                btn.setTitle("标题\(index)", forState: UIControlState.Normal)
                btn.frame = CGRect(x: 375*index, y: 0, width: 375, height: 444)
                print(375*index);
                btn.backgroundColor = UIColor(colorLiteralRed: Float(random()%10)/10.0, green: Float(random()%10)/10.0, blue: Float(random()%10)/10.0, alpha: 1)
                return btn
        }
//        把ScrollerView添加到View上
        view.addSubview(sv)
    }

    //带有参数的闭包
    func creatScrollerView(btncount:()->Int,btnSubView:(index:Int)->UIView) -> UIScrollView
    {
        let sv = UIScrollView(frame: CGRect(x: 0, y: 20, width: 375, height: 444))

        sv.backgroundColor = UIColor(colorLiteralRed: 0.7, green:0.2, blue: 0.3, alpha: 1);

        view.addSubview(sv);

        let btnCount = btncount()//执行闭包,获取数字
        var width:Float = 0.0;
        for i in 0..<btnCount
        {
            let subview = btnSubView(index: i)//执行第二个闭包获取UIView
            sv.addSubview(subview)
            width += Float(subview.bounds.size.width)

        }
        sv.contentSize = CGSize(width:CGFloat(width), height: 444)
        sv.pagingEnabled = true;
        return sv

    }
}
用闭包实现简单的小例子 ,点击屏幕更改当前界面的背景颜色
import UIKit

class ViewController: UIViewController {

//    声明一个闭包
    var finished:(()->())?

    override func viewDidLoad() {
        super.viewDidLoad()
        //用weak修饰防止循环引用
        weak var weakSelf = self;
        //执行方法
        loadTime { () -> () in
            NSLog("执行更换背景颜色");
            //颜色是随机值
            weakSelf?.view.backgroundColor = UIColor(colorLiteralRed: Float(random()%10)/10.0, green: Float(random()%10)/10.0, blue: Float(random()%10)/10.0, alpha: 1)
        }


    }
//    方法
    func loadTime(finished:()->())
    {
        NSLog("执行超时操作");
        self.finished = finished;
    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

        //触发闭包
        finished!()
    }



}
ps:

使用weak 修饰来防止闭包的循环引用问题。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WMSmile

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值