NSAttributedString을 편하게 사용하고
가운데 정렬과 text line 간의 height까지 적용할 수 있는 메서드입니다~!
extension NSMutableAttributedString {
func attributeString(string: String, font: UIFont?, textColor: UIColor, lineSpace: CGFloat? = nil, isCenter: Bool = false) -> NSMutableAttributedString {
var attributes: [NSAttributedString.Key: Any] = [
.font: font ?? UIFont.boldSystemFont(ofSize: 16),
.foregroundColor: textColor
]
let paragraphStyle = NSMutableParagraphStyle()
// 텍스트 line 간의 height 설정
if let lineSpace = lineSpace {
paragraphStyle.lineSpacing = lineSpace
}
// 텍스트의 가운데 정렬
if isCenter {
paragraphStyle.alignment = .center
}
attributes[.paragraphStyle] = paragraphStyle
self.append(NSAttributedString(string: string, attributes: attributes))
return self
}
}
NSMutableAttributedString()
.attributeString(
string: "일주일 동안\n",
font: .systemFont(ofSize: 18, weight: .bold),
textColor: .black,
lineSpace: 10,
isCenter: true
)
.attributeString(
string: "총 ",
font: .systemFont(ofSize: 18, weight: .bold),
textColor: .black,
isCenter: true
)
.attributeString(
string: "4000 걸음",
font: .systemFont(ofSize: 40, weight: .bold),
textColor: .blue,
isCenter: true
)
.attributeString(
string: " 을 걸었어요!",
font: .systemFont(ofSize: 18, weight: .bold),
textColor: .black,
isCenter: true
)