Add a prefix to TextField in SwiftUI

后端 未结 5 580
我寻月下人不归
我寻月下人不归 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条回答
  •  Happy的楠姐
    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!
            }
        }
    

提交回复
热议问题