|
//: A UIKit based Playground for presenting user interface |
|
|
|
import UIKit |
|
import PlaygroundSupport |
|
|
|
extension NSAttributedString { |
|
static func make(html: String, size: CGFloat, color: UIColor) -> NSAttributedString? { |
|
// TODO: Size is configured programatically which means we can |
|
// change it dynamically if needed (aka dynamic type) |
|
|
|
let style = """ |
|
body { |
|
color: \(color.hexString!); |
|
font-family: -apple-system; |
|
font-size: \(size)px; |
|
} |
|
b { |
|
font-weight: 600; |
|
color: hotpink; |
|
} |
|
""" |
|
|
|
let template = """ |
|
<!doctype html> |
|
<html> |
|
<head> |
|
<style> |
|
\(style) |
|
</style> |
|
</head> |
|
<body> |
|
\(html) |
|
</body> |
|
</html> |
|
""" |
|
|
|
guard let data = template.data(using: .utf8) else { |
|
return nil |
|
} |
|
|
|
guard let attributedString = try? NSAttributedString( |
|
data: data, |
|
options: [.documentType: NSAttributedString.DocumentType.html], |
|
documentAttributes: nil) else { |
|
return nil |
|
} |
|
|
|
return attributedString |
|
} |
|
} |
|
|
|
extension UIColor { |
|
var hexString: String? { |
|
if let components = cgColor.components, components.count == 3 { |
|
let r = components[0] |
|
let g = components[1] |
|
let b = components[2] |
|
return String(format: "#%02x%02x%02x", (Int)(r * 255), (Int)(g * 255), (Int)(b * 255)) |
|
} |
|
return "000000" |
|
} |
|
} |
|
|
|
class MyViewController : UIViewController { |
|
override func loadView() { |
|
let view = UIView() |
|
view.backgroundColor = .white |
|
|
|
|
|
let html = """ |
|
Let's test <b>bold</b>.<br><br>And a link <a href="http://google.com">google</a>. |
|
""" |
|
|
|
let data = Data(html.utf8) |
|
|
|
let a = NSAttributedString.make(html: html, size: 18, color: .brown) |
|
|
|
print(a) |
|
|
|
|
|
let label = UITextView() |
|
label.frame = CGRect(x: 20, y: 200, width: 200, height: 100) |
|
label.attributedText = a |
|
|
|
label.linkTextAttributes = [ |
|
.foregroundColor: UIColor.red, |
|
.underlineColor: UIColor.clear |
|
] |
|
|
|
view.addSubview(label) |
|
self.view = view |
|
} |
|
} |
|
// Present the view controller in the Live View window |
|
PlaygroundPage.current.liveView = MyViewController() |