SoulverTextKit

Swift 5.3 Platform Platform

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")
    ],
    ...
)

或在 Xcode 中添加软件包。

用法

将 SoulverTextKit 集成到你的项目中需要 3 个步骤。本仓库中提供了 NSTextView 和 UITextView 的示例。

步骤 1

在你的文本视图委托中导入 SoulverTextKit

import SoulverTextKit

步骤 2

创建 ParagraphCalculator 的实例变量,并使用你的 TextView 的 NSTextStorage 和 NSTextContainer 初始化它

    @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)
    }

步骤 3

实现 NS/UITextView textDidChange 和 NSLayoutManager didChangeGeometry 委托方法

    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()
    }

步骤 4 (可选)

阻止用户编辑段落的结果

    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 种内置样式:afterTabafterPipeafterEquals。在创建 ParagraphCalculator 时选择你偏好的样式。

After Tab (制表符后)

After Pipe (管道符后)

After Equals (等号后)

许可证

版权所有 (c) 2021 Zac Cohan。SoulverTextKit 在 MIT 许可证下分发。在商业软件中使用 SoulverCore 数学引擎需要特殊许可。你也可以修改 ParagraphCalculator 以使用其他数学引擎,如 Math.jsExpression