我正在尝试将占位符添加到使用 SwiftUI 制作的 textViews 中,但是在执行textView.text = placeholder
or时textView.text = ""
,什么也没有发生...
使用textView.insertText(placeholder)
作品,但后来我不确定如何在输入 textView 时删除占位符(textView.deleteBackward()
对于占位符中的每个字母可能)
这是我的 TextView.swift 代码:
import Foundation
import SwiftUI
struct TextView: UIViewRepresentable {
@Binding var text: String
var placeholder: String
let textStyle: UIFont.TextStyle
@Binding var isFirstResponder: Bool
let keyboard: String
func makeUIView(context: Context) -> UITextView {
let textView = UITextView()
textView.delegate = context.coordinator
textView.isSelectable = true
textView.isUserInteractionEnabled = true
textView.font = UIFont.preferredFont(forTextStyle: textStyle)
textView.textAlignment = .center
textView.autocapitalizationType = .none
textView.autocorrectionType = .no
textView.inputAssistantItem.leadingBarButtonGroups = []
textView.inputAssistantItem.trailingBarButtonGroups = []
if keyboard == "dummy" {
let dummyBoard = NumKeyboard(frame: CGRect(x: 500, y: 500, width: 0, height: 0), textView: textView)
textView.inputView = dummyBoard
} else if keyboard == "num" {
let keyboardView = NumKeyboard(frame: CGRect(x: 0, y: 0, width: 0, height: 300), textView: textView)
textView.inputView = keyboardView
keyboardView.delegate = context.coordinator
} else if keyboard == "alphaNum" {
let keyboardView = AlphaNumKeyboard(frame: CGRect(x: 0, y: 0, width: 0, height: 300),type: "UNIX", textView: textView)
textView.inputView = keyboardView
keyboardView.delegate = context.coordinator
}
textView.text = placeholder
textView.textColor = UIColor.lightGray
return textView
}
func updateUIView(_ uiView: UITextView, context: Context) {
if uiView.text != text {
uiView.text = text
}
DispatchQueue.main.async {
if self.isFirstResponder && !uiView.isFirstResponder {
uiView.becomeFirstResponder()
}
if !self.isFirstResponder && uiView.isFirstResponder {
uiView.resignFirstResponder()
}
}
}
func makeCoordinator() -> Coordinator {
Coordinator($text, $isFirstResponder, placeholder)
}
class Coordinator: NSObject, UITextViewDelegate, KeyboardDelegate {
@Binding var text: String
@Binding var isFirstResponder: Bool
var placeholder: String
init(_ text: Binding<String>, _ isFirstResponder: Binding<Bool>, _ placeholder: String) {
_text = text
_isFirstResponder = isFirstResponder
self.placeholder = placeholder
}
func textViewDidChange(_ textView: UITextView) {
self.text = textView.text
}
func textViewDidBeginEditing(_ textView: UITextView) {
if textView.textColor == UIColor.lightGray {
print(placeholder)
textView.text = nil
textView.textColor = UIColor.black
}
}
func textViewDidEndEditing(_ textView: UITextView) {
if textView.text.isEmpty {
textView.text = placeholder
textView.textColor = UIColor.lightGray
} else {
self.text = textView.text
}
}
}
}