问题
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.
回答1:
normally you should post your coding tries here, because this is not a "we code for you"-platform....but...it is a sunny day so here is the code ;)
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let textField = UITextField(frame: CGRect(x: 100, y: 100, width: 200, height: 20))
view.addSubview(textField)
textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: UIControl.Event.editingChanged)
textField.layer.borderColor = UIColor.red.cgColor
textField.layer.borderWidth = 2
}
@objc func textFieldDidChange(_ textField: UITextField) {
if textField.text?.prefix(1) != "+" {
textField.text = "+" + textField.text!
}
}
回答2:
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)
}
}
回答3:
import SwiftUI
struct ContentView: View {
@State var userName : String = ""
var body: some View {
VStack {
HStack{
Image(systemName: "plus")
TextField("placeholder",text:$userName)
}
.padding(5)
.foregroundColor(.white)
.background(Capsule().fill(Color.gray))
Spacer()
}.padding(5)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
I will say this is better approach to add "+" sign , so that you will not receive + sign when you access userName
回答4:
I required the same functionality in my app (user needs to put in country code so I can verify number) and I achieved something similar to what you want using a custom binding:
struct PrefixedTextField: View {
@State private var countryCode = "+"
var body: some View {
let countryCodeCustomBinding =
Binding(
get: { self.countryCode },
set: {
self.countryCode = $0
if self.countryCode.isEmpty { self.countryCode = "+" }
})
return TextField("+91", text: countryCodeCustomBinding).keyboardType(.numberPad)
}
}
来源:https://stackoverflow.com/questions/60427656/add-a-prefix-to-textfield-in-swiftui