Swift生成属性文本AttributedString

1.话不多说,直接上代码

let label = UILabel(frame: view.bounds)
label.textAlignment = .center
view.addSubview(label)

let myString = "Swift"
//设置文字颜色成蓝色,属性文本别的设置也几乎就是在这个字典中设置
let myAttribute = [NSForegroundColorAttributeName: UIColor.blue]
let myAttrString = NSAttributedString(string: myString, attributes: myAttribute)
label.attributedText = myAttrString

2.设置文本属性

从上面代码看出,设置文本的属性,是通过myAttribute这个字典来实现的。所以下面一一列举一些常用的设置:

1.设置背景颜色

//设置成黄色
let myAttribute = [NSBackgroundColorAttributeName: UIColor.yellow]

2.设置字体和字体大小

let myAttribute = [NSFontAttributeName: UIFont(name: "Chalkduster", size: 18.0)]

3.设置下划线

let myAttribute = [ NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue ]

4.设置阴影

let myShadow = NSShadow()
myShadow.shadowBlurRadius = 3
myShadow.shadowOffset = CGSize(width: 3, height: 3)
myShadow.shadowColor = UIColor.gray

let myAttribute = [ NSShadowAttributeName: myShadow ]

3.Attributes创建

文本的属性可以单独一个一个的创建,如下:

let singleAttribute1 = [ NSForegroundColorAttributeName: UIColor.green ]
let singleAttribute2 = [ NSBackgroundColorAttributeName: UIColor.yellow ]
let singleAttribute3 = [ NSUnderlineStyleAttributeName: NSUnderlineStyle.styleDouble.rawValue ]

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

let multipleAttributes: [String : Any] = [
    NSForegroundColorAttributeName: UIColor.green,
    NSBackgroundColorAttributeName: UIColor.yellow,
    NSUnderlineStyleAttributeName: NSUnderlineStyle.styleDouble.rawValue ]

同时,也可以自定义属性上去

let customAttribute = [ "MyCustomAttributeName": "Some value" ]

或者创建出一个属性字典,然后依次添加key-value进去

var multipleAttributes = [String : Any]()
multipleAttributes[NSForegroundColorAttributeName] = UIColor.green
multipleAttributes[NSBackgroundColorAttributeName] = UIColor.yellow
multipleAttributes[NSUnderlineStyleAttributeName] = NSUnderlineStyle.styleDouble.rawValue

4.创属性字符串

1.通过string创建

let attrString1 = NSAttributedString(string: "Hello.")

2.通过string创建,同时附加自定义属性

let attrString2 = NSAttributedString(string: "Hello.", attributes: ["MyCustomAttribute": "A value"])

3.通过string和特定的属性创建

let myAttributes1 = [ NSForegroundColorAttributeName: UIColor.green ]
let attrString3 = NSAttributedString(string: "Hello.", attributes: myAttributes1)

4.如果需要改变属性或者改变内容,则可以创建出可变的属性字符串

let mutableAttrString1 = NSMutableAttributedString()

5.可变属性文本使用

首先,创建出可变属性文本

let myString = "Swift"
        //设置文字颜色成蓝色,富文本别的设置也几乎就是在这个字典中设置
        let myAttribute = [ NSForegroundColorAttributeName: UIColor.red ]
        let myAttrString = NSMutableAttributedString(string: myString, attributes: myAttribute)
        label.attributedText = myAttrString

然后给属性文本添加新的样式的属性文本

let afterString = NSAttributedString(string: "是Apple力推的语言!")
myAttrString.append(afterString)

label.attributedText = myAttrString

然后给指定区间的字符串设定特定的属性

let myRange = NSRange(location: 6, length: 5)
myAttrString.addAttribute(NSForegroundColorAttributeName, value: UIColor.green, range: myRange)

label.attributedText = myAttrString

可以在已有的属性基础上再次添加属性

let range = NSRange(location: 0, length: myAttrString.length)
myAttrString.addAttribute(NSBackgroundColorAttributeName, value: UIColor.yellow, range: range)

label.attributedText = myAttrString

5.添加图片

使用

let attachment = NSTextAttachment(data: nil, ofType: nil)
attachment.image = UIImage(named: "image.png")
attachment.bounds = CGRect(x: 0, y: 0, width: 20, height: 20)
let image_text = NSAttributedString(attachment: attachment)
myAttrString.append(image_text)

6.Swift4的改变

在Swift4下,NSFontAttributeName等等,已经被统一成NSAttributedStringKey结构体的类属性中去了,所以,应该写成NSAttributedStringKey.font。

[NSAttributedStringKey.underlineStyle: NSUnderlineStyle.styleSingle.rawValue]

7.Swift5 文字中添加链接(NSMutableAttributedString)

let ruleAstr = NSMutableAttributedString.init(string: "登录及代表阅读并同意服务条款")
let pstyle = NSMutableParagraphStyle()
pstyle.alignment = NSTextAlignment.center
ruleAstr.addAttributes([NSAttributedString.Key.paragraphStyle : pstyle], range: NSRange(location: 0, length: ruleAstr.length))

ruleAstr.addAttributes([NSAttributedString.Key.foregroundColor : UIColor.lightGray], range: NSRange(location: 0, length: ruleAstr.length))
ruleAstr.addAttributes([NSAttributedString.Key.font : FONT12], range: NSRange(location: 0, length: ruleAstr.length))

ruleAstr.addAttributes([NSAttributedString.Key.foregroundColor : kMainBlueColor], range: ruleAstr.mutableString.range(of: "服务条款"))
ruleAstr.addAttribute(NSAttributedString.Key.link, value: URL(string: "ruleAct")!, range: ruleAstr.mutableString.range(of: "服务条款"))
ruleT.attributedText = ruleAstr
ruleT.isEditable = false
ruleT.delegate = self
extension LoginVC: UITextViewDelegate {
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
        if URL.absoluteString == "ruleAct" {
            JJLog("点击条款")
        }
        return false
    }
}

results matching ""

    No results matching ""