Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> iOS

Cách dùng chữ In đậm (Bold) và thường (Non-Bold) trong một UILabel iOS

Để hiển thị vừa chữ in đậm (Bold) vừa chữ thường (Regular) trong một UILabel, chúng ta có 2 cách: chỉnh sửa trên Storyboard hoặc làm bằng code (programmatically).

Phương pháp 1: Chỉnh sửa trên Storyboard

  1. Chọn Label cần chỉnh, vào Attribute Inspector.
  2. Ở mục Text, chọn Attributed thay vì Plain.
  3. Gõ nội dung: "Bold Regular" (trong đó "Bold" là phần muốn in đậm).
  4. Double-click chọn từ "Bold", chuột phải > Font > chọn Bold.
  5. Kết quả hiển thị ngay trên Storyboard.

Phương pháp 2: Lập trình (Programmatically) – Khuyến khích cho dynamic content

Sử dụng NSAttributedString để kết hợp nhiều style trong một label:

override func viewDidLoad() {
    super.viewDidLoad()
    
    let boldAttribute: [NSAttributedString.Key: Any] = [
        .font: UIFont(name: "HelveticaNeue-Bold", size: 18)!
    ]
    
    let regularAttribute: [NSAttributedString.Key: Any] = [
        .font: UIFont(name: "HelveticaNeue-Light", size: 18)!
    ]
    
    let boldText = NSAttributedString(string: "Bold", attributes: boldAttribute)
    let regularText = NSAttributedString(string: " regular", attributes: regularAttribute)
    
    let combined = NSMutableAttributedString()
    combined.append(boldText)
    combined.append(regularText)
    
    lbl.attributedText = combined
}

Cách dùng chữ In đậm (Bold) và thường (Non-Bold) trong một UILabel iOS

Mẹo nâng cao

Chuyển logic trên thành extension để tái sử dụng:

extension UILabel {
    func setMixedText(bold: String, regular: String, fontSize: CGFloat = 18) {
        let boldAttrs: [NSAttributedString.Key: Any] = [.font: UIFont.boldSystemFont(ofSize: fontSize)]
        let regularAttrs: [NSAttributedString.Key: Any] = [.font: UIFont.systemFont(ofSize: fontSize)]
        
        let attributed = NSMutableAttributedString(string: bold, attributes: boldAttrs)
        attributed.append(NSAttributedString(string: regular, attributes: regularAttrs))
        self.attributedText = attributed
    }
}

// Sử dụng:
label.setMixedText(bold: "Tên: ", regular: "Nguyễn Văn A")

Lưu ý: Nên dùng UIFont.boldSystemFont(ofSize:) và UIFont.systemFont(ofSize:) thay vì hardcode tên font "HelveticaNeue" để tương thích Dynamic Type và hệ thống.