SwiftyRichText
一个适用于 Swift 的富文本 (NSAttributedString
) 处理库。
安装
CocoaPods
pod 'SwiftyRichText'
Carthage
github "HjzCy/SwiftyRichText"
使用
需要多行显示时,先设置 UILabel
的 numberOfLines
属性。
import UIKit
class ViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
URLSession.shared.dataTask(with: URL(string: "https://app.meinali.com/all/?a=show&c=cailiao&id=291")!) { (data, response, err) in
if let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
if let content = (json?["retData"] as? [String: Any])?["content"] as? String {
DispatchQueue.main.async {
let cell = self.tableView.cellForRow(at: IndexPath(row: 2, section: 0))
let html = """
<font style=\"font-size:14px\">\(content)</font>
<style>img{display:block;margin:auto;}</style>
""".toHTML // NSAttributedString
// 给页面添加行间距和段落间距
cell?.textLabel?.attributedText = html?.append(.pClosure { (style) in
style.lineSpacing = 5
style.paragraphSpacing = 10
})
cell?.textLabel?.attributedText = html
self.tableView.reloadData()
}
}
}
}.resume()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!
if indexPath.row == 0 {
cell.textLabel?.attributedText = "决斗当日".addAttributes(.font(.systemFont(ofSize: 28)), .color(.blue))
.add("谢尔兹和林肯按照约定来到密西西比河畔,".addAttributes(.font(.systemFont(ofSize: 17))))
.add("在岸上对峙。".addAttributes(.backColor(.red)))
.add("两人都做好了战斗致死的准备。".addAttributes(.strikethrough(.styleSingle)))
.add("幸运的是,".addAttributes(.font(.systemFont(ofSize: 14)), .color(.white), .backColor(.black)))
.add("在".addAttributes())
.add("千钧一发".addAttributes(.font(.systemFont(ofSize: 28)), .underline(.styleSingle)))
.add("之际,两个人的支持者及时赶到,".addAttributes(.font(.systemFont(ofSize: 14))))
.add("阻止了悲剧的发生。".addAttributes(.font(.systemFont(ofSize: 17)), .color(.yellow), .backColor(.gray)))
}else if indexPath.row == 1 {
cell.textLabel?.attributedText = "0.00\n账号余额".addAttributes(.pClosure { (style) in
style.lineSpacing = 5
style.alignment = .center
})
}
return cell
}
}
APIs
属性
public enum Attribute {
/// 前景颜色
case color(UIColor)
/// 背景颜色
case backColor(UIColor)
/// 字体
case font(UIFont)
/// 段落1
case pStyle(NSMutableParagraphStyle)
/// 段落2
case pClosure((NSMutableParagraphStyle) -> Void)
/// 删除线
case strikethrough(NSUnderlineStyle)
/// 删除线颜色
case strikethroughColor(UIColor)
/// 删除线加颜色
case strikethroughWithColor(NSUnderlineStyle, UIColor)
/// 下划线
case underline(NSUnderlineStyle)
/// 下划线颜色
case underlineColor(UIColor)
/// 下划线和颜色
case underlineWithColor(NSUnderlineStyle, UIColor)
}
字符串
public extension String {
/// 添加多个属性
func addAttributes(_ attrs: Attribute...) -> NSMutableAttributedString
/// 添加单个属性,文字默认为黑色
func addAttributes(_ attrs: Attribute = .color(.black)) -> NSMutableAttributedString
/// 转换成 HTML 格式的属性字符串
var toHTML: NSMutableAttributedString?
}
NSMutableAttributedString
public extension NSMutableAttributedString {
/// 添加属性字符串
/// 如果传入的属性字符串没有 .font 属性,则同步上一个的 font
@discardableResult
func add(_ attrStr: NSAttributedString) -> NSMutableAttributedString
/// 替换指定节点字符串
func replace(at index: Int, with str: String)
/// 替换指定节点属性字符串
func replace(at index: Int, with attrString: NSAttributedString)
/// 重置指定节点属性
func set(_ attrs: Attribute..., at index: Int)
/// 给指定节点字符串追加属性
func add(_ attrs: Attribute..., at index: Int)
/// 给整段字符串追加属性
func add(_ attrs: Attribute...)
}
NSAttributedString
public extension NSAttributedString {
/// 返回指定节点的属性字典
func attributes(at index: Int) -> [NSAttributedStringKey: Any]
/// 获取指定节点的所在范围
func range(at index: Int) -> NSRange
/// 返回指定节点的属性字符串
subscript(index: Int) -> NSAttributedString
/// 返回指定节点的字符串
subscript(index: Int) -> String
}
最后
如果您在使用过程中有任何问题或宝贵建议,请及时提出,感谢使用!