您的位置:首页 > 移动开发 > Swift

swift基本语法(总结提炼版)之013 swift 之闭包返回值

2016-05-24 23:47 323 查看

1.代码

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

let sc = createScrollView({ () -> Int in
return 15
}) { (index) -> UILabel in
let width = 50
let label = UILabel()
label.backgroundColor = UIColor.greenColor()
label.textColor = UIColor.darkGrayColor()
label.font = UIFont.systemFontOfSize(17)
label.text = "text\(index)"
label.frame = CGRect(x: index * width, y: 0, width: width, height: 44)
return label
}
view.addSubview(sc)

}

}

/**
这个函数有两个闭包参数: labelCount: ()->Int labelWithIndex: (index:Int)->UILabel
这个函数的返回值是一个UIScrollView
*/

func createScrollView(labelCount: ()->Int, labelWithIndex: (index:Int)->UILabel) -> UIScrollView{
// 1.创建UIScrollView
let sc = UIScrollView(frame: CGRect(x: 0, y: 100, width: 375, height: 44))

let count = labelCount()
// let width = 50

// 2.遍历创建UILabel
for i in 0..<count{

let label = labelWithIndex(index: i)
sc.addSubview(label)
sc.contentSize = CGSize(width: CGFloat(count) * label.bounds.width, height: 44)
}

// 返回UIScrollView
return sc
}
//}

2.效果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: