我想让文本“突出显示”,但不是整个文本框。我希望每一行都单独突出显示。我还没有找到实现这一目标的最佳方法。我唯一能想到的就是使用变量中的相同文本,在其上放置背景颜色,将字体降低到产生间隙的位置并使文本颜色清晰......如果这有意义的话。这就是我想要的。我正在使用 SwiftUI。任何帮助将不胜感激。
重要的是,这就是我用来实现文本对齐的方法。
struct LabelAlignment: UIViewRepresentable {
var text: String
var textAlignmentStyle : TextAlignmentStyle
var width: CGFloat
var fontName: String
var fontSize: CGFloat
var fontColor: UIColor
func makeUIView(context: Context) -> UILabel {
let font = UIFont(name: fontName, size: fontSize)
let label = UILabel()
label.textAlignment = NSTextAlignment(rawValue: textAlignmentStyle.rawValue)!
label.numberOfLines = 0
label.preferredMaxLayoutWidth = width
label.font = font
label.setContentHuggingPriority(.required, for: .horizontal)
label.setContentHuggingPriority(.required, for: .vertical)
label.textColor = fontColor
return label
}
func updateUIView(_ uiView: UILabel, context: Context) {
uiView.text = text
}
}
enum TextAlignmentStyle : Int{
case left = 0 ,center = 1 , right = 2 ,justified = 3 ,natural = 4
}
具有行间距和背景颜色的属性文本
func updateUIView(_ uiView: UILabel, context: Context) {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 15
let attributedText = NSAttributedString(
string: "This is a quote from my favorite book. I will put many more of these quotes on this list. Enjoy for now thank you",
attributes: [
.backgroundColor: UIColor.yellow,
.paragraphStyle: paragraphStyle,
])
uiView.attributedText = attributedText
}