Add a prefix to TextField in SwiftUI

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

提交回复
热议问题