我正在尝试使用以下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
不可变,想知道是否有解决方法
答案 0 :(得分:0)
这些“链接方法”不应变异。如果您查看可以在SwiftUI框架中链接的方法,则这些方法都不会标记为mutating
。 Quick example。
这些方法应该返回结构的新实例,并更改某些属性。
即像这样:
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)
}