我知道这是一个老问题,但我一直在寻找 SoundCloud 在其标签上的相同效果。这是 uilabel 的子类
import UIKit
class LabelPine: UILabel {
override func drawTextInRect(rect: CGRect) {
let insets = UIEdgeInsets.init(top: 5, left: 0, bottom: 5, right: 3)
super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets))
}
override func textRectForBounds(bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
super.textRectForBounds(bounds, limitedToNumberOfLines: 0)
return CGRectInset(self.attributedText!.boundingRectWithSize(CGSizeMake(999, 999), options: .UsesLineFragmentOrigin, context: nil), -5, -5)
}
}
这是各个类的实现:
labelNombre = LabelPine()
labelNombre?.text = nombreUser
labelNombre?.frame = CGRectMake(10, nombrePos.Yo, nombrePos.ancho, nombrePos.alto)
labelNombre?.font = UIFont(name:"Hiragino Sans W3",size: 19)!
labelNombre?.textAlignment = .Left
labelNombre?.backgroundColor = UIColor(white: 1, alpha: 0.5)
labelNombre?.textColor = colorBlentUIColor
labelNombre?.sizeToFit()
header?.addSubview(labelNombre!)
注意我调用 sizeToFit()。