「Swift」AttributedString常见使用方法

前言:AttributedString是Apple推出的可以实现单个字符或字符范围带相应属性的字符串。属性提供了一些文本特性,可以让文本展示的样式更加丰富。在日常开发过程中,我通常用于同一个Label中包含不同的字体大小或字体颜色的样式编写中。

使用举例

需求:需要设置一个红底白字的Label

swift 复制代码
attributedLabel = UILabel()

let contentStr = NSString(string: "AttributedString")
let attStr = NSMutableAttributedString(string: contentStr as String)
attStr.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 20, weight: .medium), range: NSRange(location: 0, length: contentStr.length))
attStr.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.white, range: NSRange(location: 0, length: contentStr.length))
attStr.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.red, range: NSRange(location: 0, length: contentStr.length))
attributedLabel.attributedText = attStr

样式展示:

文本属性介绍

从上方代码可以看出,文本的属性是通过设置文本字体,文本颜色,文本背景颜色所实现的。所以下面来一一列举一些常用的文本属性及展示效果。

  • 设置文本字体大小和粗细
swift 复制代码
attStr.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 20, weight: .medium), range: NSRange(location: 0, length: contentStr.length))

效果:

  • 设置文本颜色
swift 复制代码
attStr.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.blue, range: NSRange(location: 0, length: contentStr.length))

效果:

  • 设置背景颜色
swift 复制代码
attStr.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.red, range: NSRange(location: 0, length: contentStr.length))

效果:

  • 设置下划线
swift 复制代码
attStr.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: NSRange(location: 0, length: contentStr.length))

效果:

  • 设置下划线颜色

默认下划线颜色与文本颜色相同

swift 复制代码
attStr.addAttribute(NSAttributedString.Key.underlineColor, value: UIColor.green, range: NSRange(location: 0, length: contentStr.length))

效果:

  • 拼接文本

先设置好相关文本属性,然后将其相互连接

swift 复制代码
let contentStr1 = NSString(string: "Attributed")
let attStr1 = NSMutableAttributedString(string: contentStr1 as String)
attStr1.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 20, weight: .medium), range: NSRange(location: 0, length: contentStr1.length))
attStr1.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.blue, range: NSRange(location: 0, length: contentStr1.length))

let contentStr2 = NSString(string: "String")
let attStr2 = NSMutableAttributedString(string: contentStr2 as String)
attStr2.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 12, weight: .medium), range: NSRange(location: 0, length: contentStr2.length))
attStr2.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.green, range: NSRange(location: 0, length: contentStr2.length))

attStr1.append(attStr2)
        
attributedLabel.attributedText = attStr1

效果:

Attributes创建及使用

attributes可以一次性创建多个属性,attributes是一个字典

需求:创建一个红底白字的Label

swift 复制代码
let contentStr = NSString(string: "AttributedString")
let attStr = NSMutableAttributedString(string: contentStr as String)
attStr.addAttributes([NSAttributedString.Key.font: UIFont.systemFont(ofSize: 20, weight: .regular),
                      NSAttributedString.Key.foregroundColor : UIColor.white,
                      NSAttributedString.Key.backgroundColor : UIColor.red], range: NSRange(location: 0, length: contentStr.length))

attributedLabel.attributedText = attStr

效果:

常用属性方法整合

我将常用的一些文本属性进行整合了一个类

swift 复制代码
import Foundation
import UIKit

public struct ZUAttributedString {
    
    public enum Font:String {
        case thin = "PingFangSC-Thin"
        case light = "PingFangSC-Light"
        case medium = "PingFangSC-Medium"
        case regular = "PingFangSC-Regular"
    }
    
    public enum Line{
        case none
        case midLine
        case underLine
    }
    
    public static func attributeString(content:String,
                                font: UIFont,
                                alignment:NSTextAlignment? = NSTextAlignment.center,
                                textColor:UIColor?,
                                backgroundColor: UIColor? = nil,
                                line:Line = .none,
                                lineSpacing:CGFloat = 0) -> NSMutableAttributedString
    {
        let contentStr = NSString(string: content)
        let attStr = NSMutableAttributedString(string: contentStr as String)
        
        //set color
        if let textColor = textColor {
            attStr.addAttribute(NSAttributedString.Key.foregroundColor, value: textColor, range: NSRange(location: 0, length: contentStr.length))
        }
        if let backgroundColor = backgroundColor {
            attStr.addAttribute(NSAttributedString.Key.backgroundColor, value: backgroundColor, range: NSRange(location: 0, length: contentStr.length))
        }
        
        let style = NSMutableParagraphStyle()
        if let align = alignment {
            style.alignment = align
            
        } else {
            style.alignment = NSTextAlignment.center
        }
        
        if lineSpacing > 0{
            style.lineSpacing = lineSpacing
        }
        
        attStr.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: NSRange(location: 0, length: contentStr.length))
        
        attStr.addAttribute(NSAttributedString.Key.font, value: font, range: NSRange(location: 0, length: contentStr.length))
        
        switch line{
        case .none:
            break
        case .midLine:
            attStr.addAttribute(NSAttributedString.Key.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: NSMakeRange(0, attStr.length))
            break
        case .underLine:
            attStr.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: NSMakeRange(0, attStr.length))
            break
            
        }
        
        return attStr
    }
    
    public static func attributeString(content:String,
                                font:ZUAttributedString.Font,
                                size:CGFloat,
                                alignment:NSTextAlignment? = NSTextAlignment.center,
                                textColor:UIColor?,
                                backgroundColor:UIColor? = nil,
                                line:Line = .none,
                                maximumLineHeight:CGFloat) -> NSMutableAttributedString
    {
        let attStr = NSMutableAttributedString(string: content)
        
        //set color
        if let textColor = textColor {
            attStr.addAttribute(NSAttributedString.Key.foregroundColor, value: textColor, range: NSRange(location: 0, length: content.count))
        }
        if let backgroundColor = backgroundColor {
            attStr.addAttribute(NSAttributedString.Key.backgroundColor, value: backgroundColor, range: NSRange(location: 0, length: content.count))
        }
        
        let style = NSMutableParagraphStyle()
        if let align = alignment {
            style.alignment = align
        } else {
            style.alignment = NSTextAlignment.center
        }
        
        attStr.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: NSRange(location: 0, length: content.count))
        
        
        //set font
        switch font {
        case .thin:
            let font = UIFont(name: ZUAttributedString.Font.thin.rawValue, size: size) ?? UIFont.systemFont(ofSize: size)
            attStr.addAttribute(NSAttributedString.Key.font, value: font, range: NSRange(location: 0, length: content.count))
        case .light:
            let font = UIFont(name: ZUAttributedString.Font.light.rawValue, size: size) ?? UIFont.systemFont(ofSize: size)
            attStr.addAttribute(NSAttributedString.Key.font, value: font, range: NSRange(location: 0, length: content.count))
            break
        case .medium:
            let font = UIFont(name: ZUAttributedString.Font.medium.rawValue, size: size) ?? UIFont.systemFont(ofSize: size)
            attStr.addAttribute(NSAttributedString.Key.font, value: font, range: NSRange(location: 0, length: content.count))
            break
        case .regular:
            let font = UIFont(name: ZUAttributedString.Font.regular.rawValue, size: size) ?? UIFont.systemFont(ofSize: size)
            attStr.addAttribute(NSAttributedString.Key.font, value: font, range: NSRange(location: 0, length: content.count))
            break
        }
        
        switch line{
        case .none:
            break
        case .midLine:
            attStr.addAttribute(NSAttributedString.Key.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: NSMakeRange(0, attStr.length))
            break
        case .underLine:
            attStr.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: NSMakeRange(0, attStr.length))
            break
            
        }
        
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.maximumLineHeight = maximumLineHeight
        // Line spacing attribute
        attStr.addAttribute(NSAttributedString.Key.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attStr.length))
    
        return attStr
    }
}

方法使用:

swift 复制代码
let attStr1 = ZUAttributedString.attributeString(content: "Attributed", font: UIFont.systemFont(ofSize: 20, weight: .regular), textColor: UIColor.green, backgroundColor: nil)
let attStr2 = ZUAttributedString.attributeString(content: "String", font: UIFont.systemFont(ofSize: 20, weight: .regular), textColor: UIColor.blue, backgroundColor: nil)

attStr1.append(attStr2)

效果:

所以通过方法整合的方式,可以更加方便便捷的使用AttributedString,并且也可以更好的实现我们目标的文本样式

参考文章

iOS swift 带有attributeString的多行文本label

Swift生成属性文本AttributedString

如果该文章对你有所帮助,可以点赞、收藏并且关注一下! 后续会持续更新更多技术内容

相关推荐
missmisslulu2 小时前
电容笔值得买吗?2024精选盘点推荐五大惊艳平替电容笔!
学习·ios·电脑·平板
GEEKVIP3 小时前
手机使用技巧:8 个 Android 锁屏移除工具 [解锁 Android]
android·macos·ios·智能手机·电脑·手机·iphone
GEEKVIP3 小时前
如何在 Windows 10 上恢复未保存/删除的 Word 文档
macos·ios·智能手机·电脑·word·笔记本电脑·iphone
奇客软件4 小时前
iPhone使用技巧:如何恢复变砖的 iPhone 或 iPad
数码相机·macos·ios·电脑·笔记本电脑·iphone·ipad
奇客软件1 天前
如何从相机的记忆棒(存储卡)中恢复丢失照片
深度学习·数码相机·ios·智能手机·电脑·笔记本电脑·iphone
GEEKVIP1 天前
如何修复变砖的手机并恢复丢失的数据
macos·ios·智能手机·word·手机·笔记本电脑·iphone
一丝晨光1 天前
继承、Lambda、Objective-C和Swift
开发语言·macos·ios·objective-c·swift·继承·lambda
GEEKVIP2 天前
iPhone/iPad技巧:如何解锁锁定的 iPhone 或 iPad
windows·macos·ios·智能手机·笔记本电脑·iphone·ipad
KWMax2 天前
RxSwift系列(二)操作符
ios·swift·rxswift