UILable默认是文本居中对其的,郁闷的是UILable并没有提供设置垂直方向的对齐方式。所以就只有自己想办法了:
方法一:
在显示文字时,首先计算文字需要的宽高,在改变UILable的宽高,这种方式比就不多说了。
方法二:
利用swift的extension特性去修改UILable的绘制代码(OC的category),示例代码如下:
extension UILabel {
//UILable 文字上对其
func alignTop() -> Void {
guard self.text?.isEmpty == false else {
return
}
self.lineBreakMode = .byCharWrapping //以字符为显示单位显示,后面部分省略不显示
let size = CGSize(width: self.frame.width, height: CGFloat(MAXFLOAT))
let dic = NSDictionary(object: self.font, forKey: NSFontAttributeName as NSCopying)
let fontSize = self.text?.boundingRect(with: size, options: .truncatesLastVisibleLine, attributes: dic as? [String : AnyObject], context:nil).size
let newLinesToPad = (self.frame.height - (fontSize?.height)!)/(fontSize?.height)!
for _ in 0..<Int(newLinesToPad) {
self.text = self.text?.appending("\n ")
}
}
//UILable 文字下对齐
func alignBottom() -> Void {
guard self.text?.isEmpty == false else {
return
}
self.lineBreakMode = .byCharWrapping //以字符为显示单位显示,后面部分省略不显示
let size = CGSize(width: self.frame.width, height: CGFloat(MAXFLOAT))
let dic = NSDictionary(object: self.font, forKey: NSFontAttributeName as NSCopying)
let fontSize = self.text?.boundingRect(with: size, options: .truncatesLastVisibleLine, attributes: dic as? [String : AnyObject], context:nil).size
let newLinesToPad = (self.frame.height - (fontSize?.height)!)/(fontSize?.height)!
for _ in 0..<Int(newLinesToPad) {
self.text = String(format: " \n%@", self.text!)
}
}
}