import UIKit
class ViewController:UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let ary = ["ni","hao","shi","jie","ni","hao","shi","jie"]
let scroll = creatScrollView({ () ->Int in
// 返回要 创建 lab的数目
return ary.count
}, lable: { (index) ->UILabel in
// 创建完成一个lab 返回
let lab = UILabel()
lab.text = ary[index]
lab.textAlignment =NSTextAlignment.Center
lab.font =UIFont.systemFontOfSize(14)
lab.sizeToFit()
return lab
})
self.view .addSubview(scroll)
}
// 返回 scrollView
func creatScrollView(numberLable : () -> Int,lable : (index : Int) -> UILabel) -> UIScrollView{
// 创建 scrollView
let scrollView = UIScrollView(frame:CGRectMake(0,50, 320, 50))
// 获得lable 的数目
let num = numberLable()
var margin : (CGFloat) =8
var labW : (CGFloat) =50
// swift 可以直接拿到 height 不用通过 size
var labH : (CGFloat) = scrollView.frame.height
var labX : (CGFloat) =0
// 循环添加
for i in 0..<num{
let lab = lable(index: i)
// swift对格式要求非常严格,没有隐式转换, 所以 不能 Int * CGFloat
// var labX : (CGFloat) = (CGFloat)(i * (labW + margin))
lab.frame =CGRectMake(labX, 20, labW, labH)
labX += labW + margin
scrollView.addSubview(lab)
}
scrollView.contentSize =CGSizeMake(labX, labH)
scrollView.showsHorizontalScrollIndicator =false
return scrollView
}