UICollectionView可以創(chuàng)建高度不一的瀑布流,但是沒有辦法處理寬度不一的標(biāo)簽流.現(xiàn)在我們就用代碼來自己創(chuàng)建一個標(biāo)簽流,會分別使用frame硬編碼布局和autolayout自動布局兩種方式來實現(xiàn)
一. frame硬編碼布局
最終完成效果如下
- 新建一個Single View Application的iOS Project,我們就在初始創(chuàng)建的ViewController上面編寫代碼
- 我們創(chuàng)建數(shù)據(jù)源(TagLabel是一個自定義的UILabel,加入了文本和邊框的padding,也可以直接使用UILabel,一樣可以實現(xiàn)效果)
var dataSource = [String]()
var labels = [TagLabel]()
//mock 數(shù)據(jù)數(shù)量
let count = 20
- 在viewDidLoad中初始化數(shù)據(jù)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
for _ in 0..<count {
dataSource.append(RandomString.sharedInstance.getRandomStringOfLength(3 + Int(arc4random_uniform(7))))
}
for i in 0..<count {
labels.append(TagLabel())
labels[i].text = dataSource[i]
labels[i].padding = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
labels[i].layer.borderColor = UIColor.greenColor().CGColor
labels[i].layer.borderWidth = 1
labels[i].layer.cornerRadius = 8
self.view.addSubview(labels[i])
}
layoutLabels()
}
- 布局標(biāo)簽流
func layoutLabels() {
let width = UIScreen.mainScreen().bounds.width
//標(biāo)簽間水平間距
let horizontalSpace : CGFloat = 12
//標(biāo)簽行間距
let verticalSpace : CGFloat = 12
//左邊已經(jīng)填充長度
var left : CGFloat = 0
//頂部已經(jīng)填充高度
var top : CGFloat = 0
var lineLabels = [[TagLabel]]()
var lineLabel = [TagLabel]()
var lineStartSpace = [CGFloat]()
for label in labels {
let labelWidth = label.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).width
if left + labelWidth + horizontalSpace > width {
lineLabels.append(lineLabel)
lineLabel = [TagLabel]()
lineStartSpace.append((width - left + horizontalSpace) / 2)
left = 0
}
left += labelWidth + horizontalSpace
lineLabel.append(label)
}
lineLabels.append(lineLabel)
lineStartSpace.append((width - left + horizontalSpace) / 2)
top = verticalSpace + 20
var size : CGSize = CGSize.zero
for (index, oneLine) in lineLabels.enumerate() {
left = lineStartSpace[index]
for label in oneLine {
size = label.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
label.frame = CGRect(x: left, y: top, width: size.width, height: size.height)
left += size.width + horizontalSpace
}
top += size.height + verticalSpace
}
}
- RandomString是我自己寫的一個生成隨機長度的字符串方法,代碼如下:
///隨機字符串生成
class RandomString {
let characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
/**
生成隨機字符串,
- parameter length: 生成的字符串的長度
- returns: 隨機生成的字符串
*/
func getRandomStringOfLength(length: Int) -> String {
var ranStr = ""
for _ in 0..<length {
let index = Int(arc4random_uniform(UInt32(characters.characters.count)))
ranStr.append(characters[characters.startIndex.advancedBy(index)])
}
return ranStr
}
private init() {
}
static let sharedInstance = RandomString()
}
- 以上就是硬編碼布局標(biāo)簽流的所有代碼了,運行看看效果吧~
二. AutoLayout自動布局
待續(xù)...
完整代碼見Github: https://github.com/growold/SwiftLearn 的Learn02TagFlow項目.