在 SwiftUI 中为 TextField 添加前缀 [英] Add a prefix to TextField in SwiftUI
问题描述
我想在 文本字段 中添加一个无法擦除的+"号.用户应该能够在它之后输入值,如果他按下退格键,它应该只擦除他输入的值.当我输入任何其他数字时,它会自动在输入值的开头添加一个+".
I want a ‘+’ Sign in the Textfield which cannot be erased. A user should be able to enter values after it and if he presses backspace it should only erase the value he entered. And when I write any other number it will automatically add a ‘+’ at the beginning of the enter value.
例如:-我想在文本字段中添加国家/地区代码,因此,只要用户开始输入,+"就会自动添加到字段的开头国家代码.
For Example:- I want to add country code in the textfield so, '+' automatically add in the beginning of the field as soon as user start typing a country code.
推荐答案
在 SwiftUI 中,您可能希望使用 Combine 框架来执行此操作.创建一个 ObservableObject
来处理值的变化.示例代码在这里:
In SwiftUI, you may want to use Combine framework to do this. Create an ObservableObject
to handle value changes. Example code here:
import SwiftUI
import Combine
struct ContentView: View {
class ViewModel: ObservableObject {
@Published var text = "" {
didSet {
if text.prefix(1) != "+" {
text = "+" + text
}
}
}
}
@ObservedObject var viewModel = ViewModel()
var body: some View {
TextField("Placeholder", text:$viewModel.text)
}
}
这篇关于在 SwiftUI 中为 TextField 添加前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!