只需使用几个就会容易得多UILabel
s 如果你想要圆角。
如果这是可以接受的,您可以首先生成一个属性字符串数组,例如:
func getAttributedStrings(text: String) -> [NSAttributedString]
{
let words:[String] = text.componentsSeparatedByString(" , ")
let attributes = [NSForegroundColorAttributeName: UIColor.whiteColor(), NSBackgroundColorAttributeName: UIColor.blueColor()]
let attribWords = words.map({
return NSAttributedString(string: " \($0) ", attributes: attributes)
})
return attribWords
}
对于每个属性字符串,我们需要创建UILabel
。为此,我们可以创建一个函数,传入一个NSAttributedString
并返回一个UILabel
:
func createLabel(string:NSAttributedString) ->UILabel
{
let label = UILabel()
label.backgroundColor = UIColor.blueColor()
label.attributedText = string
label.sizeToFit()
label.layer.masksToBounds = true
label.layer.cornerRadius = label.frame.height * 0.5
return label
}
现在我们将输入字符串转换为标签:
let attribWords = getAttributedStrings("Java , Swift , JavaScript , Objective-C , Ruby , Pearl , Lisp , Haskell , C++ , C")
let labels = attribWords.map { string in
return createLabel(string)
}
现在我们只需要在视图中显示它们:
let buffer:CGFloat = 3.0
var xOffset:CGFloat = buffer
var yOffset:CGFloat = buffer
let view = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 320.0, height: 400.0))
view.backgroundColor = UIColor.lightGrayColor()
for label in labels
{
label.frame.origin.x = xOffset
label.frame.origin.y = yOffset
if label.frame.maxX > view.frame.maxX
{
xOffset = buffer
yOffset += label.frame.height + buffer
label.frame.origin.x = xOffset
label.frame.origin.y = yOffset
}
view.addSubview(label)
xOffset += label.frame.width + buffer
}
此时,我们还可以通过以下命令将视图大小调整为标签的高度:
if let labelHeight = labels.last?.frame.height
{
view.frame.height = yOffset + labelHeight + buffer
}
Throwing this code in a swift playground results in:
如果您不能使用标签,如果您想要可编辑的UITextView
例如,我会放弃圆角,只说:
let attribWords = getAttributedStrings("Java , Swift , JavaScript , Objective-C , Ruby , Pearl , Lisp , Haskell , C++ , C")
let attribString = NSMutableAttributedString()
attribWords.forEach{
attribString.appendAttributedString(NSAttributedString(string: " "))
attribString.appendAttributedString($0)
}
textView.attributedText = attribString