[Swift] NSAttributedString for using html Tag

Seonhu Kim·2023년 4월 30일
0

Swift

목록 보기
4/7
post-thumbnail

UILabel에 HTML 태그를 인식해서 적용하려면 NSAttributedString 타입을 사용한다.

한글 폰트의 경우 html 태그가 적용이 되더라도, 본래 UILabel에 정의된 폰트나 설정 값들은 적용이 안되었는데, 잘 정리한 블로그 내용이 있어 참고했다.

extension String {
    func htmlEscaped(font: UIFont, colorHex: String, lineSpacing: CGFloat) -> NSAttributedString {
        let style = """
                    <style>
                    p.normal {
                      line-height: \(lineSpacing);
                      font-size: \(font.pointSize)px;
                      font-family: \(font.familyName);
                      color: \(colorHex);
                    }
                    </style>
        """
        let modified = String(format:"\(style)<p class=normal>%@</p>", self)
        do {
            guard let data = modified.data(using: .unicode) else {
                return NSAttributedString(string: self)
            }
            let attributed = try NSAttributedString(data: data,
                                                    options: [.documentType: NSAttributedString.DocumentType.html],
                                                    documentAttributes: nil)
            return attributed
        } catch {
            return NSAttributedString(string: self)
        }
    }
}

String의 html 태그를 그대로 인식하면서 폰트, 컬러 등을 동시에 적용해주는 extension이다. 해당 String을 NSAttributedString으로 반환한다.


class ViewController: UIViewController {

    @IBOutlet weak var titleLabel: UILabel!
    let sampleHtml = "<strong>안녕하세요</strong>"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        let font = UIFont(name: "AppleSDGothicNeo-Regular", size: 15)!
        titleLabel.attributedText = sampleHtml.htmlEscaped(font: font,
                                                           colorHex: "#ff6347",
                                                           lineSpacing: 1.5)
    }
}

이처럼 기존 스토리보드에 정의된 UILabel에 Html 태그를 사용하면서 폰트와 컬러를 정의할 수 있다.

profile
iOS Developer.

0개의 댓글