์ด๋ฏธ์ง์ ๊ธ์๊ฐ ์๋ Button์ ๋ง๋ค๋ค๊ฐ, String์์ image๋ฅผ ๋ฃ์ ์ ์๋ค๋ ๊ฒ์ ์์๋ค!
NSAttributedString
ํ ์คํธ ์ผ๋ถ์ ๋ํด ํน์ฑ(์๊ฐ์ ์คํ์ผ, ํ์ดํผ ๋งํฌ ๋ฑ)์ด ์๋ ๋ฌธ์์ด
ํ
์คํธ ์ผ๋ถ์ ๋ํด ํน์ฑ๋ค์ ์ ์ฉํ ์ ์๋ String์ด๋ค. ๊ธฐ๋ณธ์ ์ผ๋ก Read-only์ด๋ค. default font๋ก๋ Helvetica 12-point๋ฅผ ์ฌ์ฉํ๋ค. NSParagraphStyle
์ ์ฌ์ฉํ๋ฉด ์ ๋ ฌ, indent, lineSpacing, lineBreakMode ๋ฑ์ ์ถ๊ฐํ์ฌ ์ฌ์ฉํ ์ ์๋ค. ๋ค์๊ณผ ๊ฐ์ ๊ฒ๋ค์ด ๊ฐ๋ฅํ๋ค.
- ๋ถ๋ถ์ font ์ ์ฉ
- kerning (์๊ฐ)
- ๋ถ๋ถ์ Color ์ ์ฉ
- markdown์ผ๋ก ๋ถํฐ ์์ฑ
- html์ผ๋ก๋ถํฐ ์์ฑ
let text = "์ถ๊ฐํ๊ธฐ"
var attributes = [NSAttributedString.Key: Any]()
attributes[.font] = font
attributes[.foregroundColor] = color
attributes[.kern] = value
attributes[.strokeWidth] = width
attributes[.strokeColor] = color
let style = NSMutableParagraphStyle()
style.minimumLineHeight = minimumLineHeight
style.maximumLineHeight = maximumLineHeight
style.lineSpacing = lineSpacing
style.lineBreakMode = lineBreakMode
attributes[.paragraphStyle] = style
let attributedString = NSAttributedString(string: text, attributes: attr?.rawValue)
NSTextAttachment๋ก ์ด๋ฏธ์ง ๋ฃ๊ธฐ
ํน์ ํ๋์ ์์์ image + Label๊ณผ ๊ฐ์ ํ์์ผ๋ก ๋ฃ์ด์ฃผ์ด์ผ ํ ๋๊ฐ ์๋ค. ์ฌ๊ฐ ๊ท์ฐฎ์ ๊ฒ์ด ์๋๋ฐ, ์ด๋ฌํ ๊ฒฝ์ฐ NSTextAttachment
์ NSAttributedString
์ ์ฌ์ฉํ์ฌ ์ฒ๋ฆฌํ๋ ๋ฐฉ๋ฒ๋ ์๋ค.
let font = UIFont.systemFont(ofSize: 14)
let image = UIImage(name: "addtion")
let imageSize = CGSize(width: 12, height: 12)
let text = "์ถ๊ฐํ๊ธฐ"
let attachment = NSTextAttachment()
attachment.image = image
let y = (font.capHeight - imageSize.height).rounded() / 2 // font ๋๋น center
attachment.bounds = CGRect(x: 0, y: y, width: imageSize.width, height: imageSize.height)
[NSAttributedString(attachment: attachment), NSAttributedString.makeSpace(points: self.spacing), attributedString].joined()
์ฌ๊ธฐ์ font ์๋ฃ์ด์ฃผ๋ฉด default font๋ก ์ ์ฉ๋์ ์ํ๋ ๋ชจ์์ด ์๋์ฌ ์ ์๋ค. ์๋ margin์ด ์๊ฒผ๋ ๊ฒ์ผ๋ก ๊ธฐ์ตํ๋ค.