ใช้ Attributed String เพื่อผสมสไตล์ข้อความใน UILabel เดียว ได้ 2 วิธี: Storyboard และ โค้ด
วิธีที่ 1: ใช้ Storyboard (Attributed Text)
- เลือก UILabel → Attribute Inspector
- ที่ Text เลือก Attributed แทน Plain
- พิมพ์ข้อความ เช่น "Bold Regular"
- เลือกคำว่า "Bold" → คลิกขวา → Font → Bold
วิธีที่ 2: โปรแกรมด้วย NSAttributedString
override func viewDidLoad() {
super.viewDidLoad()
let boldAttrs: [NSAttributedString.Key: Any] = [
.font: UIFont.boldSystemFont(ofSize: 18),
.foregroundColor: UIColor.label
]
let regularAttrs: [NSAttributedString.Key: Any] = [
.font: UIFont.systemFont(ofSize: 18),
.foregroundColor: UIColor.secondaryLabel
]
let boldText = NSAttributedString(string: "Bold ", attributes: boldAttrs)
let regularText = NSAttributedString(string: "Regular", attributes: regularAttrs)
let combined = NSMutableAttributedString()
combined.append(boldText)
combined.append(regularText)
label.attributedText = combined
}
Extension ใช้งานง่าย
extension UILabel {
func setMixedText(bold: String, regular: String, fontSize: CGFloat = 17, boldColor: UIColor = .label, regularColor: UIColor = .label) {
let boldAttrs: [NSAttributedString.Key: Any] = [
.font: UIFont.boldSystemFont(ofSize: fontSize),
.foregroundColor: boldColor
]
let regularAttrs: [NSAttributedString.Key: Any] = [
.font: UIFont.systemFont(ofSize: fontSize),
.foregroundColor: regularColor
]
let attributed = NSMutableAttributedString(string: bold, attributes: boldAttrs)
attributed.append(NSAttributedString(string: regular, attributes: regularAttrs))
self.attributedText = attributed
}
}
// ใช้งาน
label.setMixedText(bold: "ราคา: ", regular: "฿1,290", fontSize: 16)
สไตล์เพิ่มเติมที่ทำได้
- Italic:
.font: UIFont.italicSystemFont(ofSize: size) - Underline:
.underlineStyle: NSUnderlineStyle.single.rawValue - Strikethrough:
.strikethroughStyle: NSUnderlineStyle.single.rawValue - Link:
.link: URL(string: "...")