Add a prefix to TextField in SwiftUI

后端 未结 5 589
我寻月下人不归
我寻月下人不归 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)
        }
    }
    

提交回复
热议问题