Skip to content

Instantly share code, notes, and snippets.

@TuenTuenna
Last active September 3, 2021 07:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TuenTuenna/7dc00f0afbdec50b86b8e29063ee9a1b to your computer and use it in GitHub Desktop.
Save TuenTuenna/7dc00f0afbdec50b86b8e29063ee9a1b to your computer and use it in GitHub Desktop.
html css 적용 attributed label 스트링 익스텐션

Swift String -> Html attributed 스트링으로 변환 css 적용 시키기

extension String {

  func htmlAttributedStringWithStyle(to label : UILabel) -> NSAttributedString? {
        
        let width = UIScreen.main.bounds.width
        print("현재 디바이스 넓이 : width: \(width)")
        
        let deviceType = DeviceSize(rawValue: width)
        
        var widthSize = 360
        
        switch deviceType {
        case .iPhoneSE:
            widthSize = 300
        case .iPhone6andX:
            widthSize = 360
        case .iPhone7and8Max:
            widthSize = 360
        case .none:
            widthSize = 360
        }
        
        let htmlTemplate = """
        <!doctype html>
        <html>
        <meta name="viewport" content="width=device-width, initial-scale=1">
          <head>
            <style>
         
            .container {
                font-family: Helvetica;
                text-align: center;
                width: \(widthSize)px;
                height: 300px;
                overflow: hidden;
              }
              .container > img {
                position: absolute;
                width: 100%;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
              }
            </style>
        <script >alert(screen.width);</script>
        </head>
          <body>
            <div class="container">
            \(self)
            </div>
          </body>
        </html>
        """

        guard let data = htmlTemplate.data(using: .unicode) else {
            return nil
        }

        guard let attributedString = try? NSAttributedString(
            data: data,
            options: [.documentType: NSAttributedString.DocumentType.html],
            documentAttributes: nil
            ) else {
            return nil
        }

        return attributedString
    }
    
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment