์ด๋ฏธ์ง€์™€ ๊ธ€์ž๊ฐ€ ์žˆ๋Š” 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์ด ์ƒ๊ฒผ๋˜ ๊ฒƒ์œผ๋กœ ๊ธฐ์–ตํ•œ๋‹ค.

Reference