Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 238
Ravindra_Bhati Avatar asked Feb 27 '20 06:02

Ravindra_Bhati


2 Answers

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)
    }
}
like image 165
Bijoy Thangaraj Avatar answered Sep 24 '22 00:09

Bijoy Thangaraj


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!
        }
    }
like image 33
Chris Avatar answered Sep 24 '22 00:09

Chris