Add a prefix to UITextField

后端 未结 4 1436
故里飘歌
故里飘歌 2021-01-22 02:18

I want a \'$\' Sign in the text field which cannot be erased. A user should be able to enter values after it and if he presses backspace it should only erase the value he entere

4条回答
  •  终归单人心
    2021-01-22 02:38

    You can subclass UITextField for all the text field which take amount as value.

    class SpecialTextField: UITextField {
    
    var amount: String {
        get {
            if self._amount.characters.count > 1 {
                return (self._amount as NSString).substringFromIndex(2)
            }
            return ""
        }
    }
    
    // MARK: - UITextField Observing
    override internal func willMoveToSuperview(newSuperview: UIView!) {
        if newSuperview != nil {
            keyboardType = .DecimalPad
            addTarget(self, action: #selector(SpecialTextField.didChangeText), forControlEvents: .EditingChanged)
        }
    }
    
    override internal func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool {
        return false
    }
    
    
    private var newVal: String = ""
    private var _amount: String = ""
    
    func didChangeText() {
        if (text?.characters.count > 2) {
            if text?.rangeOfString("$ ") == nil {
                text = newVal
            }
        }
    
        if (text?.characters.count == 1) && (text?.characters.count > newVal.characters.count) {
            text = "$ " + text!
        }
        if (text?.characters.count == 2) && (text?.characters.count < newVal.characters.count) {
            text = ""
        }
        newVal = text ?? ""
        _amount = newVal
    }
    }
    

    This will insert a $ sign whenever first number is entered, and removes it whenever all the numbers are removed.

    var amount will give the actual amount value user has entered, after removing the $ sign.

    Hope this helped.

提交回复
热议问题