psharanda / Atributika

Convert text with HTML tags, links, hashtags, mentions into NSAttributedString. Make them clickable with UILabel drop-in replacement.
MIT License
1.45k stars 155 forks source link

href support #45

Closed abhikpo closed 6 years ago

abhikpo commented 6 years ago

Hi, href are not working. The following code snippet is an example. Can you look into it where we did the mistake? Also, unable to click Facebook link. If I am displaying as Facebook.com, it is clickable.

    let href = "<a href=\"https://www.google.com/\">Google.com</a>  href  <a href=\"https://www.facebook.com/\">Facebook</a>"

    let a = Style("a").foregroundColor(.green).underlineStyle(.styleSingle)
    let all = Style.font(.systemFont(ofSize: 20.0)).foregroundColor(.gray)
    let link = Style.foregroundColor(.green, .normal).foregroundColor(.red, .highlighted)

    hrefLink.attributedText = href.style(tags: a)
        .styleAll(all)
        .styleLinks(link)

    hrefLink.numberOfLines = 0

    hrefLink.onClick = { label, detection in
        switch detection.type {
        case .tag(let tag):
            let t = tag.attributes
            if let href = t["href"] {
                if let url = URL(string: href) {
                    if #available(iOS 10.0, *) {
                        UIApplication.shared.open(url, options: [:]
                            , completionHandler: nil)
                    } else {
                        // Fallback on earlier versions
                    }
                }
            }
        case .link(let url):
            UIApplication.shared.open(url, options: [:]
                , completionHandler: nil)
        default:
            break
        }
    }
psharanda commented 6 years ago

styleLinks - detects and styles regular links in text (not placed in tags). So you need just add .higlighted support to 'a' style

  let href = "<a href=\"https://www.google.com/\">Google.com</a>  href  <a href=\"https://www.facebook.com/\">Facebook</a>"

    let all = Style.font(.systemFont(ofSize: 20.0)).foregroundColor(.gray)
    let a = Style("a").foregroundColor(.green, .normal).foregroundColor(.red, .highlighted)

    hrefLink.attributedText = href.style(tags: a)
        .styleAll(all)