You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在NSAttributedString中调整文本与下划线的间距?

调整NSAttributedString文本与下划线的间距

方案1:iOS 15+ 原生属性直接设置

从iOS 15开始,系统提供了NSUnderlineOffsetAttributeName属性,可直接控制下划线与文本的垂直间距,正值会让下划线向下偏移,拉开和文本的距离:

let attributedString = NSMutableAttributedString(string: "你的目标文本")
// 设置下划线样式与颜色
attributedString.addAttribute(.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: NSRange(location: 0, length: attributedString.length))
attributedString.addAttribute(.underlineColor, value: UIColor.black, range: NSRange(location: 0, length: attributedString.length))
// 调整下划线偏移量,值越大,下划线越靠下,间距越大
attributedString.addAttribute(.underlineOffset, value: 4, range: NSRange(location: 0, length: attributedString.length))

// 赋值给UILabel/UITextView
yourLabel.attributedText = attributedString

方案2:iOS 14及以下 兼容方案

低版本系统无专门的下划线偏移属性,可通过调整baselineOffset配合下划线样式实现需求:

let attributedString = NSMutableAttributedString(string: "你的目标文本")
let underlineStyle = NSUnderlineStyle.single.rawValue | NSUnderlineStyle.patternSolid.rawValue
attributedString.addAttribute(.underlineStyle, value: underlineStyle, range: NSRange(location: 0, length: attributedString.length))
attributedString.addAttribute(.underlineColor, value: UIColor.black, range: NSRange(location: 0, length: attributedString.length))
// 调整基线偏移,带动下划线下移,注意值不宜过大避免文本位置异常
attributedString.addAttribute(.baselineOffset, value: 2, range: NSRange(location: 0, length: attributedString.length))

yourLabel.attributedText = attributedString

方案3:自定义绘制下划线(完全可控)

若上述方案无法满足需求,可自定义UILabel子类,手动绘制下划线,实现对位置、粗细、间距的完全控制:

class UnderlinedLabel: UILabel {
    var underlineOffset: CGFloat = 4 // 文本与下划线的间距
    var underlineThickness: CGFloat = 1 // 下划线粗细
    var underlineColor: UIColor = .black
    
    override func draw(_ rect: CGRect) {
        super.draw(rect)
        
        guard let text = text, !text.isEmpty else { return }
        
        let textRect = self.textRect(forBounds: rect, limitedToNumberOfLines: numberOfLines)
        let underlineY = textRect.origin.y + textRect.size.height + underlineOffset
        let underlineRect = CGRect(x: textRect.origin.x, y: underlineY, width: textRect.size.width, height: underlineThickness)
        
        let path = UIBezierPath(rect: underlineRect)
        underlineColor.setFill()
        path.fill()
    }
}

使用时直接配置子类属性:

let customLabel = UnderlinedLabel()
customLabel.text = "你的目标文本"
customLabel.underlineOffset = 4
customLabel.underlineColor = .black

内容的提问来源于stack exchange,提问作者Gagan_iOS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 11:22:51