swift 基础语法4

一、闭包的基本使用:

创建一个swift项目:

闭包类似于oc中block,可以通过下面的代码看出:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        /*闭包的基本格式
        {
            () -> ()
            in
            需要执行的代码
        }
        */
        
       /*闭包的几种格式:
        1、将闭包通过实参传递给函数
        2、如果闭包是函数的最后一个参数,那么闭包可以写在()的后面
        3、如果韩式只接受一个参数,并且这个参数是闭包,那么这个()可以省略
        */
        
        /*
          闭包的简写:
        如果闭包没有参数也没有返回值,那么in之前的东西都可以删除,包括in
        */
        
        loadData { () -> () in
            print("被回调了")
        }
        
    }
    
    func loadData(finished:()->())
    {
        print("执行耗时操作")
        
        finished()
    }

    override func touchesBegan(touches: Set, withEvent event: UIEvent?) {
        dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
            print(NSThread.currentThread())
            print("执行耗时的操作")
            
            
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                print(NSThread.currentThread())
                print("回到主线程刷新UI")
                
            })
        }
    }
    

}


二、闭包的参数和返回值

实现一个UI界面。

uiscrollview上面添加了N个button,可以滚动uisrollview

要求:定义一个方法来创建UIScrollview

1、并且UIScrollview上有多少个按钮必须通过闭包的形式告诉该方法

2、并且如何创建按钮也需要通过闭包来创建

swift 基础语法4_第1张图片

//
//  ViewController.swift
//  闭包的返回值和参数
//
//  Created by base on 16/09/19.
//  Copyright © 2016年 base. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
      let sc = creatScrollView({ () -> Int in
        return 5
        }) { (index) -> UIView in
            let width = 80
            let btn = UIButton()
            //3、设置UIButton的属性
            btn.setTitle("标题\(index)", forState: UIControlState.Normal)
            btn.frame = CGRect(x : index * width, y:0, width:width,height: 44)
            //4、将uibutton添加到UIScrollview上面
           return btn
        }
        
        //5、将UIScrollview添加到控制器上面
        view.addSubview(sc)
    }

   
    //要求:定义一个方法来创建UIScrollview

    func creatScrollView(btnCount: () -> Int,btnWithIndex:(index:Int) -> UIView) -> UIScrollView
    {
        //1、创建一个scrollview
        
        let sc = UIScrollView(frame: CGRect(x: 0, y: 100, width: 375, height: 44))
        sc.backgroundColor = UIColor.redColor()
        
//        let width = 80
        //2、创建N多个uibutton
        let count = btnCount()
        for i in 0..

你可能感兴趣的:(swift,闭包)