SoulverTextKit 允许你向任何 NSTextView 或 UITextView 添加逐行计算功能。它使用 SoulverCore 进行数值计算,SoulverCore 还提供单位转换、日期和时间计算等功能。
SoulverTextKit 使用 Swift Package Manager 分发。要将其安装到项目中,只需将其作为依赖项添加到你的 Package.swift 清单文件中
let package = Package(
...
dependencies: [
.package(url: "https://github.com/soulverteam/SoulverTextKit.git", from: "0.0.1")
],
...
)
将 SoulverTextKit 集成到你的项目中需要 3 个步骤。本仓库中提供了 NSTextView 和 UITextView 的示例。
import SoulverTextKit
@IBOutlet var textView: NSTextView!
var paragraphCalculator: SoulverTextKit.ParagraphCalculator!
override func viewDidLoad() {
super.viewDidLoad()
self.paragraphCalculator = ParagraphCalculator(answerPosition: .afterEquals, textStorage: self.textView.textStorage, textContainer: self.textView.textContainer)
}
func textDidChange(_ notification: Notification) {
// Let us know when the text changes, so we can evaluate any changed lines if necessary
paragraphCalculator.textDidChange()
}
func layoutManager(_ layoutManager: NSLayoutManager, textContainer: NSTextContainer, didChangeGeometryFrom oldSize: NSSize) {
// Let us know when the text view changes size, so we can change update the formatting if necessary
paragraphCalculator.layoutDidChange()
}
func textView(_ textView: NSTextView, shouldChangeTextIn affectedCharRange: NSRange, replacementString: String?) -> Bool {
// Check with us to see if the user should be able to edit parts of the paragraph.
switch paragraphCalculator.shouldAllowReplacementFor(affectedCharRange: affectedCharRange, replacementString: replacementString) {
case .allow:
return true
case .deny:
NSSound.beep()
return false
case .setIntertionPoint(range: let range):
textView.setSelectedRange(range)
return false
}
}
计算段落有 3 种内置样式:afterTab、afterPipe 和 afterEquals。在创建 ParagraphCalculator 时选择你偏好的样式。
版权所有 (c) 2021 Zac Cohan。SoulverTextKit 在 MIT 许可证下分发。在商业软件中使用 SoulverCore 数学引擎需要特殊许可。你也可以修改 ParagraphCalculator 以使用其他数学引擎,如 Math.js 或 Expression。