Add a prefix to UITextField

隐身守侯 提交于 2019-12-02 03:27:47

问题


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 entered.

The reason I can't use UILabel before it is because the text in UITextfield is center aligned and it grows to either side as the user enters values.

Please provide any solution


回答1:


  1. Set the text field's text to "$" initially.
  2. Set the text field's delegate to some object of yours (probably the view controller containing it).
  3. Implement -textField:shouldChangeCharactersInRange:replacementString: and return NO if the proposed change would delete the "$".

Also, you might need to implement -textFieldDidBeginEditing: to position the cursor after the "$" if it's not there already.




回答2:


No need to use shouldChangeCharactersInRange delegate method. The easiest and most convenient solution is this

            var label = UILabel(frame: CGRectMake(0, 0, 50, 50))
            label.text = "$";
            label.backgroundColor = UIColor(white: 0.0, alpha: 0.0)
            tenantField.rightViewMode = .Always
            tenantField.rightView = label



回答3:


As noted in the previous answer Add a prefix to UITextField

inside the textFieldDidBeginEditing as delegate method i found using the following code to be best and right way to format string we are pre/post fixing currency symbols/codes

        NSNumberFormatter* formatter = [[NSNumberFormatter alloc]init];
        [formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
        [formatter setPaddingPosition:NSNumberFormatterPadAfterPrefix];
        [formatter setCurrencySymbol:symbol];
        [formatter setMaximumFractionDigits:2];
        [formatter setMinimumFractionDigits:2];
        [formatter setUsesGroupingSeparator:YES];
        [formatter setCurrencyGroupingSeparator:@","];
        [formatter setCurrencyDecimalSeparator:@"."];



回答4:


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.



来源:https://stackoverflow.com/questions/9756454/add-a-prefix-to-uitextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!