7

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.

Chris
  • 7,579
  • 3
  • 18
  • 38
Ravindra_Bhati
  • 1,071
  • 13
  • 28
  • There might be confusion here, so please clarify, do you need to add '+' it in *model* value as well of only in TextFiled UI? – Asperi Feb 27 '20 at 10:33

6 Answers6

5

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)
    }
}
Bijoy Thangaraj
  • 5,434
  • 4
  • 43
  • 70
0

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!
        }
    }
Chris
  • 7,579
  • 3
  • 18
  • 38
0
  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

Kishore Kumar
  • 4,265
  • 3
  • 26
  • 47
0

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)
    }
}
rayaantaneja
  • 1,182
  • 7
  • 18
0

Try replacing the "+" with my "kg"

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        var amountTypedString = myTF.text
        if string.count > 0 {
            if amountTypedString?.count ?? 0 > 2 {
                amountTypedString = String((amountTypedString?.dropLast(2))!)
            }
            amountTypedString! += string
            let newString = amountTypedString! + "kg"
            myTF.text = newString
        } else {
            amountTypedString = String((amountTypedString?.dropLast(3))!)
            if (amountTypedString?.count)! > 0 {
                let newString = amountTypedString! + "kg"
                myTF.text = newString
            } else {
                myTF.text = ""
            }
        }
        return false
    }
0

Here is the working Code

import SwiftUI import Combine

class ViewModel: ObservableObject {
    @Published var text = "" {
        didSet {
            if text.prefix(1) != "+"{
            if text.count == 1{
                text = "+" + amount
            }
        }
        if text.prefix(0) == "+" && text.prefix(1) == ""{
            text = ""
        }
    }
}

@ObservedObject var viewModel = ViewModel()

var body: some View {
    TextField("Placeholder", text:$viewModel.text)
}
RakeshDipuna
  • 1,570
  • 13
  • 19