因此,我的目标是有一种更方便的方法在SwiftUI的TextEditor
上添加占位符文本值,因为似乎没有占位符文本值。我尝试的方法发现了一些关于Binding<>
封装类型的我真的不理解的地方。(也许这是一个危险信号,表明我正在做一些不推荐的事情?(
不管怎样,我的问题是:我们是否能够以编程方式更新Binding
s上的底层值?如果我接受一些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
}
}
}
}
}
}
根据您的要求自定义此设置:
struct ContentView: View {
@State private var text: String = ""
var body: some View {
VStack {
ZStack(alignment: .leading) {
if self.text.isEmpty {
VStack {
Text("Placeholder Text")
.multilineTextAlignment(.leading)
.padding(.leading, 25)
.padding(.top, 8)
.opacity(0.5)
Spacer()
}
}
TextEditor(text: $text)
.padding(.leading, 20)
.opacity(self.text.isEmpty ? 0.5 : 1)
}
.frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height/2)
.overlay(
Rectangle().stroke()
.foregroundColor(Color.black)
.padding(.horizontal, 15)
)
}
}
}