在swift中使用属性字符串使文本加粗 [英] Making text bold using attributed string in swift
本文介绍了在swift中使用属性字符串使文本加粗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的字符串
var str = "@text1 this is good @text1"
现在用另一个字符串替换text1
,比如t 1
.我可以替换文本,但无法将其加粗.我想将新字符串 t 1
加粗,以便最终输出:
Now replace text1
with another string, say t 1
. I am able to replace the text, but i am not able to bold it. I want to bold the new string t 1
, so that the final output will be:
@t 1这很好@t 1
我该怎么做?
我看到的所有例子都是用 Objective-C 写的,但我想用 Swift 来做.
All the examples I am seeing are in Objective-C, but I want to do it in Swift.
提前致谢.
推荐答案
用法:
let label = UILabel()
label.attributedText =
NSMutableAttributedString()
.bold("Address: ")
.normal(" Kathmandu, Nepal
")
.orangeHighlight(" Email: ")
.blackHighlight(" prajeet.shrestha@gmail.com ")
.bold("
Copyright: ")
.underlined(" All rights reserved. 2020.")
结果:
这是在单个标签中组合粗体和普通文本以及一些其他奖励方法的巧妙方法.
Here is a neat way to make a combination of bold and normal texts in a single label plus some other bonus methods.
扩展:Swift 5.*
extension NSMutableAttributedString {
var fontSize:CGFloat { return 14 }
var boldFont:UIFont { return UIFont(name: "AvenirNext-Bold", size: fontSize) ?? UIFont.boldSystemFont(ofSize: fontSize) }
var normalFont:UIFont { return UIFont(name: "AvenirNext-Regular", size: fontSize) ?? UIFont.systemFont(ofSize: fontSize)}
func bold(_ value:String) -> NSMutableAttributedString {
let attributes:[NSAttributedString.Key : Any] = [
.font : boldFont
]
self.append(NSAttributedString(string: value, attributes:attributes))
return self
}
func normal(_ value:String) -> NSMutableAttributedString {
let attributes:[NSAttributedString.Key : Any] = [
.font : normalFont,
]
self.append(NSAttributedString(string: value, attributes:attributes))
return self
}
/* Other styling methods */
func orangeHighlight(_ value:String) -> NSMutableAttributedString {
let attributes:[NSAttributedString.Key : Any] = [
.font : normalFont,
.foregroundColor : UIColor.white,
.backgroundColor : UIColor.orange
]
self.append(NSAttributedString(string: value, attributes:attributes))
return self
}
func blackHighlight(_ value:String) -> NSMutableAttributedString {
let attributes:[NSAttributedString.Key : Any] = [
.font : normalFont,
.foregroundColor : UIColor.white,
.backgroundColor : UIColor.black
]
self.append(NSAttributedString(string: value, attributes:attributes))
return self
}
func underlined(_ value:String) -> NSMutableAttributedString {
let attributes:[NSAttributedString.Key : Any] = [
.font : normalFont,
.underlineStyle : NSUnderlineStyle.single.rawValue
]
self.append(NSAttributedString(string: value, attributes:attributes))
return self
}
}
注意:如果编译器缺少 UIFont/UIColor,请将它们替换为 NSFont/NSColor.
Note: If compiler is missing UIFont/UIColor, replace them with NSFont/NSColor.
这篇关于在swift中使用属性字符串使文本加粗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文