iOS
나만의 String 만들기, NSMutableAttributedString
삼쓰 웅쓰
2019. 10. 14. 15:31
728x90
String에 폰트, 색, 굵기 등 여러가지 attributes를 주고 싶을 때 사용한다.
String attribute는 [NSAttributedString.Key: Any]의 dictionary 형태로 관리되므로, NSAttributedString.key가 attribute의 이름이 되겠다.
var multipleAttributes = [NSAttributedString.Key : Any]()
multipleAttributes[NSAttributedString.Key.foregroundColor] = UIColor.green
multipleAttributes[NSAttributedString.Key.backgroundColor] = UIColor.yellow
multipleAttributes[NSAttributedString.Key.underlineStyle] = NSUnderlineStyle.double.rawValue
NSAttributedString(
string: " 1",
attributes: multipleAttributes
)
다음과 같이 필요한 attribute들을 추가할 수 있는데 문제는 attribute를 추가하거나 다른 NSAttributedString을 추가하고 싶은 경우다.
그럴 때는 NSMutableAttributedString
을 사용한다.
let attributedQuote = NSMutableAttributedString(string: "Swift")
// add Attribute
let attributes: [NSAttributedString.Key: Any] = [.backgroundColor: UIColor.green, NSAttributedString.Key.kern: 10]
attributedQuote.addAttributes(attributes, range: NSRange(location: 0, length: 6))
// append NSAttributedString
let secondString = NSAttributedString(string: "gonna ", attributes: secondAttributes)
attributedQuote.append(secondString)