使用 UIViewRepresentable 子类链接方法

Chain methods with UIViewRepresentable subclass

我正在尝试使用以下方法实现 UITextView UIViewRepresentable

import Foundation
import SwiftUI

struct TextView: UIViewRepresentable {
    @Binding var text: String
    var _editable : Bool = true

    func makeUIView(context: Context) -> UITextView {
        let result = UITextView()
        let font = UIFont(name: "Menlo",size: 18)
        result.font = font

        return result
    }

    func updateUIView(_ uiView: UITextView, context: Context) {
        uiView.text = text
        uiView.isEditable = _editable
    }

    mutating func editable(_ editable: Bool) -> TextView {
        _editable = editable
        return self
    }
}

您会注意到我想在我的 SwiftUI 结构中使用的变异函数 editable,如下所示:

        return ZStack(alignment: Alignment.trailing) {
            TextView(text: Binding($note.content)!)
                .editable(true) // <<<< Here
            VStack {
                Text(dateString)
                    .font(.caption)
                    .foregroundColor(Color.gray)
                    .padding(3)
                Spacer()
            }
        }

但抛出以下异常:

Cannot use mutating member on immutable value: function call returns immutable value

我怀疑 UIViewRepresentable 不是可变的,想知道是否有解决办法

这些 "chained methods" 不应该发生变异。如果您查看可以在 SwiftUI 框架中链接的方法,其中 none 个标记为 mutatingQuick example.

这些方法应该return结构的新实例,其中一些属性已更改

即像这样:

func editable(_ editable: Bool) -> TextView {
    // This is a new instance of the struct, but _editable is changed to the new value
    TextView(text: $text, _editable: editable) 
}