增加 SwiftUI 中 AttributedString 的文本和下划线之间的间距

问题描述 投票:0回答:1

我想增加文本和下划线之间的间距。我尝试使用

baselineOffset
,但它增加了文本的底部间距,而不是文本和下划线之间的间距。

这是我的代码:

查看

HStack(alignment: .top, spacing: 0) {
    Image(systemName: isAgreeConditionsAndTerms ? "checkmark.square.fill" : "square")
        .font(.title2)
        .foregroundColor(isAgreeConditionsAndTerms ? .wpink : .gray)
        .padding(.trailing, 12)
        .padding(.bottom, 12)
    Text(getAttriText()).font(.system(size: 17))
}.onTapGesture {
    isAgreeConditionsAndTerms.toggle()
}

属性字符串


private func getAttriText() -> AttributedString {
    var attriString = AttributedString("I agree to the terms and conditions for posting a review".i18n)
    attriString.foregroundColor = Color(Colors.Text.black)
    
    if let privacyRange = attriString.range(of: "terms and conditions".i18n) {
        attriString[privacyRange].link = URL(string: "termanconditions://")
        attriString[privacyRange].underlineStyle = .single
        attriString[privacyRange].baselineOffset = 10
    }
    return attriString
}

结果

enter image description here

有人有办法做到这一点吗?

谢谢

ios swift swiftui
1个回答
0
投票

您可以制作自定义下划线文本组件,然后在应用程序中的任何位置使用它,并带有间距

struct UnderlinedText: View {
    let text: String
    let spacing: CGFloat
    let lineColor: Color
    let lineWidth: CGFloat
    
    init(
        _ text: String,
        spacing: CGFloat = 4,
        lineColor: Color = .blue,
        lineWidth: CGFloat = 1
    ) {
        self.text = text
        self.spacing = spacing
        self.lineColor = lineColor
        self.lineWidth = lineWidth
    }
    
    var body: some View {
        VStack(spacing: spacing) {
            Text(text)
            Rectangle()
                .frame(height: lineWidth)
                .foregroundColor(lineColor)
        }
    }
}

然后在像这样的任何视图中使用它

HStack(alignment: .top) {
        // Checkbox
        Image(systemName: "square")
            .foregroundColor(.gray)
        
        // Agreement Text
        
        Text("I agree to the")
        
        // Underlined text with custom spacing
        UnderlinedText("terms and conditions")
        
        
        Text("for posting a review")
        
    }
© www.soinside.com 2019 - 2024. All rights reserved.