Add a prefix to TextField in SwiftUI

后端 未结 5 538
我寻月下人不归
我寻月下人不归 2021-01-22 07:26

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 v

相关标签:
5条回答
  • 2021-01-22 07:37

    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)
        }
    }
    
    0 讨论(0)
  • 2021-01-22 07:40

    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 讨论(0)
  • 2021-01-22 07:47

    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!
            }
        }
    
    0 讨论(0)
  • 2021-01-22 07:56

    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)
        }
    }
    
    0 讨论(0)
  • 2021-01-22 07:58
      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

    0 讨论(0)
提交回复
热议问题