如何使在 TextField 中输入的文本不可删除? [英] How to make text typed in TextField undeletable?
问题描述
我对编程还很陌生,环顾四周后,我认为我有机会在这里问一下.我基本上需要在 TextField
中输入的文本是不可删除的,尽管可以添加/输入其他文本.
I am Fairly new to programming, after looking around I thought that id take my chances with asking here. I am basically needing for text typed in a TextField
to be undeletable, although additional text can be added/typed.
另一种方法是创建一个没有删除键的自定义键盘,尽管我在 SwiftUI 中找不到像研究等那样好的起点.
A different approach would be to create a custom keybaord without a delete key, although I couldn't find a good starting place as in research and etc for doing so in SwiftUI.
我有一个基本的 TextField
设置,带有一个空的 Binding
寻找我应该研究和/或学习的内容.
I have a basic TextField
setup with an empty Binding<String>
Looking for pointers of what I should research and or learn.
谢谢.
推荐答案
这个想法是创建 UITextField 类并使用 UIViewRepresentable 与 SwiftUI 视图绑定.这样,您可以使用所有委托方法并检测退格.此外,使用它可以防止从点击操作中剪切和删除.
The idea is the create UITextField class and use UIViewRepresentable to bind with SwiftUI view. By this, you can use all delegate methods and detect backspace. Also, using this you can prevent from cut and delete from tap action.
UndeletableTextField 自定义类
UndeletableTextField custom class
class UndeletableTextField: UITextField {
// This for prevent to cut and delete
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if action == #selector(UIResponderStandardEditActions.delete(_:)) ||
action == #selector(UIResponderStandardEditActions.cut(_:)) {
return false
}
return super.canPerformAction(action, withSender: sender)
}
}
UIViewRepresentable 视图
UIViewRepresentable view
struct UndeletableTextFieldUI: UIViewRepresentable {
@Binding var text: String
var placeholder: String
func makeUIView(context: Context) -> UndeletableTextField {
let textField = UndeletableTextField(frame: .zero)
textField.delegate = context.coordinator
textField.placeholder = placeholder
return textField
}
func updateUIView(_ uiView: UndeletableTextField, context: Context) {
uiView.text = text
}
func makeCoordinator() -> Coordinator {
Coordinator(parent: self)
}
class Coordinator: NSObject, UITextFieldDelegate {
var parent: UndeletableTextFieldUI
init(parent: UndeletableTextFieldUI) {
self.parent = parent
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
// Here we detect backspace and ignore it.
if let char = string.cString(using: String.Encoding.utf8) {
let isBackSpace = strcmp(char, "\\b")
if (isBackSpace == -92) {
print("Backspace was pressed")
return false
}
}
return true
}
}
}
内容视图
struct ContentView: View {
@State private var text: String = ""
var body: some View {
UndeletableTextFieldUI(text: $text, placeholder: "Type here")
}
}
这篇关于如何使在 TextField 中输入的文本不可删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!