NSAttributedStringBuilder13 0.4.1

NSAttributedStringBuilder13 0.4.1

Ethan Huang 维护。



NSAttributedStringBuilder

Build Status codecov GitHub release GitHub top language License Twitter Donate

使用 Flutter 风格语法组合 NSAttributedString,由功能构建器提供动力。

项目链接: https://github.com/ethanhuang13/NSAttributedStringBuilder

特性

特性
🐦 使用 Swift 5.1 编写的开源库
🍬 类似 SwiftUI 的语法
💪 支持 NSAttributedString.Key 中大部分属性
📦 使用 Swift Package Manager 进行分发
🧪 经过全面测试的代码
🛠 Swift 源兼容性测试套件 中持续集成

如何使用?

传统上我们这样组合 NSAttributedString

let mas = NSMutableAttributedString(string: "")
mas.append(NSAttributedString(string: "Hello world", attributes: [.font: UIFont.systemFont(ofSize: 24), .foregroundColor: UIColor.red]))
mas.append(NSAttributedString(string: "\n"))
mas.append(NSAttributedString(string: "with Swift", attributes: [.font: UIFont.systemFont(ofSize: 20), .foregroundColor: UIColor.orange]))

现在,使用 NSAttributedStringBuilder,我们可以用类似 SwiftUI 的语法来声明 NSAttributedString

let attributedString = NSAttributedString {
    AText("Hello world")
        .font(.systemFont(ofSize: 24))
        .foregroundColor(.red)
    LineBreak()
    AText("with Swift")
        .font(.systemFont(ofSize: 20))
        .foregroundColor(.orange)
}

要求

Xcode 11。该项目使用 Swift 5.1 功能 Function Builder

安装

Swift包

在Xcode 11中打开您的项目,导航到 菜单 -> Swift包 -> 添加包依赖 并输入 https://github.com/ethanhuang13/NSAttributedStringBuilder 进行安装。

CocoaPods

在您的Podfile中添加 pod 'NSAttributedStringBuilder13'

SwiftUI示例项目

除了更清晰的NSAttributedString语法外,由于NSAttributedStringBuilder使用函数构建器,它还使得可以在UIViewRepresentable中构建组件(它将UIView嵌入到SwiftUI的View中)。

就像SwiftUI的Text组件接受一个String作为输入一样,样本项目中AttributedText的作用是接收一个NSAttributedString作为输入并在SwiftUI中渲染。

为了实现这一点,AttributedText.swift使用@NSAttributedStringBuilder支持类似SwiftUI的语法

AttributedText.swift

然后使用AttributedText将类似于: ContentView.swift

/SwiftUISampleApp/AttributedTextSample.xcodeproj中打开样本并检查AttributedText。它使用UITextView,您也可以使用UILabelNSTextView

待办事项

  • 增强对图像附件的测试

已知问题

  • NSAttributedString 不支持链接颜色,因此具有 .color() 修饰符的 Link 组件没有任何效果。作为替代,您需要在 UITextView.linkTextAttributes.tintColor 中指定。

其他

最初在Twitter 线程中讨论。一些代码灵感来源于 zonble🙏.