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.
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)
}
}
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!
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With