SwiftUI中如何增大AttributedString文本与下划线的间距?
解决SwiftUI中AttributedString文本与下划线间距问题
问题描述
我想增大文本与下划线之间的间距,尝试使用baselineOffset,但它增大的是文本底部的间距而非文本与下划线的间距。
现有代码
View部分
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() }
AttributedString生成代码
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 }
解决方法
baselineOffset是调整文本基线位置,无法直接控制下划线与文本的间距。需要通过自定义下划线样式来设置偏移量,以下是两种适配方案:
方案1:适配iOS 15+ / macOS 12+
直接使用NSUnderlineStyle的带偏移量初始化方法:
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://") // 自定义下划线样式,设置偏移量(数值越大,下划线越靠下) let underlineStyle = NSUnderlineStyle( pattern: .solid, color: nil, // 继承文本颜色,可指定具体Color转UIColor underlineOffset: 5 ) attriString[privacyRange].underlineStyle = underlineStyle } return attriString }
方案2:适配低版本系统(iOS <15)
通过桥接NSMutableAttributedString,使用位运算设置下划线偏移:
private func getAttriText() -> AttributedString { let originalString = "I agree to the terms and conditions for posting a review".i18n let mutableAttri = NSMutableAttributedString(string: originalString) mutableAttri.addAttribute(.foregroundColor, value: UIColor(Colors.Text.black), range: NSRange(location: 0, length: originalString.count)) if let range = originalString.range(of: "terms and conditions".i18n) { let nsRange = NSRange(range, in: originalString) mutableAttri.addAttribute(.link, value: URL(string: "termanconditions://")!, range: nsRange) // 下划线样式(单下划线)+ 偏移量(左移16位后按位或,这里5为偏移值) let underlineStyle = NSUnderlineStyle.single.rawValue | NSUnderlineStyle(rawValue: 5 << 16) mutableAttri.addAttribute(.underlineStyle, value: underlineStyle, range: nsRange) // 可选:设置下划线颜色 // mutableAttri.addAttribute(.underlineColor, value: UIColor.blue, range: nsRange) } return AttributedString(mutableAttri) }
内容的提问来源于stack exchange,提问作者Nguyễn Đức Thành
相关产品推荐
相关产品推荐

