how to add % symbol at the end textField in swiftUI

Viewed 169

I want to make a custom text field which will display the amount and (%) symbol can anyone please tell me how can i acheive this. if i enter 12 it should auto insert 12%

in UIKit it will be like textField.text = "(text) %"

enter image description here

struct UiTextFieldRepresentable: UIViewRepresentable {
    @Binding var text: String
    func makeUIView(context: Context) -> some UIView {
        let textField = UITextField(frame: .zero)
        textField.placeholder = "Enter your text"
        textField.text = "\(text) %"
        return textField
    }
    func updateUIView(_ uiView: UIViewType, context: Context) {
    }
}

issue with this code is it is showing % sign before i start writing. all i want want is when i start writing in the field it should postfix the % sign

3 Answers

For the cases like this, please show your code. Because I'm not sure this is an actual question, maybe you haven't even started coding before asking it.

What exactly are you doing? To display the % symbol, just put in in the text (there're no formatting issues, it's not a special symbol etc):

struct ContentView: View {
    @State var number: Int = 12
    var body: some View {
        Text("$ \(number) %")
            .padding()
    }
}

And you'll get your view rendered:

enter image description here

TextField("", value: $input, format: .percent )

for this i made a function and on right side put a image as percentage that fixed my issue

    func makeUIView(context: Context) -> UITextField {
        let textField = UITextField(frame: .zero)
        textField.delegate = context.coordinator
        textField.tintColor = UIColor.clear
        textField.rightView = makeImageForTextField()
        textField.rightViewMode = .always
        textField.keyboardType = .decimalPad
                let toolBar = UIToolbar(
                    frame: CGRect(
                        x: 0, y: 0,
                        width: textField.frame.size.width,
                        height: 44
                    )
                )
                let doneButton = UIBarButtonItem(
                    title: "Done",
                    style: .done,
                    target: self,
                    action: #selector(textField.doneButtonTapped(button:))
                )
        
                toolBar.items = [doneButton]
                toolBar.setItems([doneButton], animated: true)
                textField.inputAccessoryView = toolBar
        return textField
    }
    
    private func makeImageForTextField() -> UIButton {
        let button = UIButton()
        button.setImage(UIImage(systemName: "percent"), for: .normal)
        button.tintColor = .black
        button.isUserInteractionEnabled = false
        return button
    }
Related