【发布时间】:2021-07-06 19:15:12
【问题描述】:
所以我的目标是有一种更方便的方法来在 SwiftUI 的 TextEditor 上添加占位符文本值,因为似乎没有。我正在尝试的方法发现了一些我对 Binding<> 包装类型真的不了解的东西。 (也许这是一个危险信号,我正在做一些不推荐的事情?)
无论如何,关于我的问题:我们是否能够以编程方式更新Bindings 上的基础值?如果我接受一些Binding<String> 值,我可以从我的方法中更新它吗?如果是这样,@State 发起者是否会引用更新后的值?下面的示例将占位符值作为文本放置在您单击它时我尝试输入的位置,如果我将其清除,甚至不会再次尝试。
从我前段时间找到的其他帖子中导入了这段代码,以便在正文为空时显示占位符。
import Foundation
import SwiftUI
struct TextEditorViewThing: View {
@State private var noteText = ""
var body: some View {
VStack{
TextEditor(text: $noteText)
.textPlaceholder(placeholder: "PLACEHOLDER", text: $noteText)
.padding()
}
}
}
extension TextEditor {
@ViewBuilder func textPlaceholder(placeholder: String, text: Binding<String>) -> some View {
self.onAppear {
// remove the placeholder text when keyboard appears
NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: .main) { (noti) in
withAnimation {
if text.wrappedValue == placeholder {
text.wrappedValue = placeholder
}
}
}
// put back the placeholder text if the user dismisses the keyboard without adding any text
NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: .main) { (noti) in
withAnimation {
if text.wrappedValue == "" {
text.wrappedValue = placeholder
}
}
}
}
}
}
【问题讨论】: