ZNSTextAttachment

ZNSTextAttachment 允许 NSTextAttachment 从远程 URL 下载图片,支持 UITextView 和 UILabel。

安装

Swift Package Manager

File > Swift Packages > Add Package Dependency
Add https://github.com/ZhgChgLi/ZNSTextAttachment.git
Select "Up to Next Major" with "1.1.9"

或者

...
dependencies: [
  .package(url: "https://github.com/ZhgChgLi/ZNSTextAttachment.git", from: "1.1.9"),
]
...
.target(
    ...
    dependencies: [
        "ZNSTextAttachment",
    ],
    ...
)

CocoaPods

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '12.0'
use_frameworks!

target 'MyApp' do
  pod 'ZNSTextAttachment', '~> 1.1.9'
end

使用方法

// ZNSTextAttachment with placeHolder Image
let attachment = ZNSTextAttachment(imageURL: URL(string: "https://zhgchg.li/assets/a5643de271e4/1*A0yXupXW9-F9ZWe4gp2ObA.jpeg")!, imageWidth: 300, placeholderImage: UIImage(systemName: "viewfinder.circle.fill")?.withTintColor(.red, renderingMode: .alwaysOriginal))

let attributedString = NSMutableAttributedString()
attributedString.append(NSAttributedString(string: "ZMarkupParser is a pure-Swift library that helps you to convert HTML strings to NSAttributedString with customized style and tags.\n"))
attributedString.append(NSAttributedString(string: "-  Parse HTML strings using pure-Swift and regular expressions.\n"))
attributedString.append(NSAttributedString(attachment: attachment))
        
attachment.dataSource = self // if not assign, will use URLSession as default
attachment.delegate = self
        
// UITextView:
textView.attributedText = attributedString

// ZNSTextAttachmentLabel, auto binding
label.attributedText = attributedString

// UILabel
attachment.register(label) // need binding
label.attributedText = attributedString

技术细节

image

文章: 手工打造 HTML 解析器的那些事(繁体中文)

关于

其他作品

Swift 库

集成工具

捐赠

Buy Me A Coffe

如果您觉得这个库有帮助,请考虑给它点亮星星或者推荐给您的朋友。

欢迎提出问题或通过 pull request 提交修复/贡献。:)