Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> iOS

วิธีใช้ Bold และ Non-Bold Text ใน UILabel เดียวกันใน iOS

ใช้ Attributed String เพื่อผสมสไตล์ข้อความใน UILabel เดียว ได้ 2 วิธี: Storyboard และ โค้ด

วิธีที่ 1: ใช้ Storyboard (Attributed Text)

  1. เลือก UILabel → Attribute Inspector
  2. ที่ Text เลือก Attributed แทน Plain
  3. พิมพ์ข้อความ เช่น "Bold Regular"
  4. เลือกคำว่า "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: "...")