粘贴字符串时如何在UITextField中保留静态前缀

时间:2015-08-05 14:37:11

标签: uitextfield uitextfielddelegate

我有一个处理货币输入的UITextField。文本字段的初始状态的设置值为$0.00,但当它成为第一个响应者时,仅更改为$

enter image description here

我已成功禁止用户通过添加以下内容删除文本字段文本的$前缀:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if textField == priceTextField {
        if range.length == 1 && count(string) == 0 {
            // Deleting text
            if range.location <= 0 {
                return false
            }
        }

    }
    return true
}

但是,这仅在用户使用键输入文本然后按退格键删除文本时才有效。如果用户复制文本,突出显示$前缀,然后在文本中粘贴,则$前缀将替换为粘贴的文本。

如果用户选择$前缀之前的位置并粘贴文本,我会将$前缀移动到替换字符串,方法是:

if range.location == 0 && count(string) >= 1 {
    textField.text = "$\(string)"
    return false
} 

我意识到我需要创建一些逻辑来使用文本字段中文本的range,但我不确定从哪里开始。

我没有要求提供代码片段,而是有人可以指出我需要实现的逻辑方向,以便$前缀不可编辑并始终在文本的开头(即使选择并粘贴)?

1 个答案:

答案 0 :(得分:0)

我建议你,

1.如果textfield为空,请使用UITextField的占位符属性来指示需要输入的内容。

2.如果文本字段有值,

i) in textFieldDidBeginEditing delegate, remove the $ symbol from the value, i.e. when textfield is active.
ii) in textFieldDidEndEditing delegate, add the $ symbol to the value entered, i.e. when textfield is inactive.