UILabel 顶部对齐 Swift
在各种调研和尝试之后,UILabel子类的方式更友好。
话不多说上代码
TopLabel
import UIKit
class TopLabel: UILabel {
var topMargin: CGFloat // 距离顶部的距离,外界可以随意设置
override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
var textRect = super.textRect(forBounds: bounds, limitedToNumberOfLines: numberOfLines)
textRect.origin.y = bounds.origin.y + topMargin
return textRect
}
override func drawText(in rect: CGRect) {
let actualRect = textRect(forBounds: rect, limitedToNumberOfLines: self.numberOfLines)
super.drawText(in: actualRect)
}
// 通过约束布局用这个
init(topMargin: CGFloat = 0) {
self.topMargin = topMargin
super.init(frame: .zero)
}
// 通过frame 布局用这个
init(frame: CGRect,topMargin: CGFloat = 0) {
self.topMargin = topMargin
super.init(frame: frame)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
应用场景
let label = TopLabel(topMargin: 5)
label.text = "hello world, do you like me?"
label.numberOfLines = 0
label.textAlignment = .left
label.backgroundColor = .red
view.addSubview(label)
label.snp.makeConstraints { make in
make.width.equalTo(150)
make.height.equalTo(200)
make.center.equalToSuperview()
}
对比一下普通UILabel的样式
SwiftUI 方式顶部对齐
SwiftUI 去完成布局时,很方便
import SwiftUI
struct ContentViewText: View {
var body: some View {
VStack(spacing: 20) {
// 普通样式
HStack {
Text("Hello world!")
Text("Hello world!")
Text("Hello world!")
Text("Hello world!")
Text("Hello world!")
}
// 顶部对齐
HStack {
Text("Hello world!")
.lineLimit(2, reservesSpace: true)
Text("Hello world!")
.lineLimit(2, reservesSpace: true)
Text("Hello world!")
.lineLimit(2, reservesSpace: true)
Text("Hello world!")
.lineLimit(2, reservesSpace: true)
Text("Hello world!")
.lineLimit(2, reservesSpace: true)
}
}
}
}
结果样式对比
这里需要解释一点,为了保持格式统一,可以给每个Text都加上lineLimit的modifier
如果不确定行数,可以将行数设置为一个区间,比如
Form {
TextField("Title", text: $model.title)
TextField("Notes", text: $model.notes, axis: .vertical)
.lineLimit(...3)
// .lineLimit(3...)
// .lineLimit(1...3)
}