UITextField 如何使 .text 在右侧键入数字时始终显示“$”符号?

UITextField how to make the .text always displaying '$' sign while typing numbers on the right side?

我有一个 UITextField,我正在接受一些输入,这些输入是用于此护理的美元。我需要实现如何在输入数字后始终显示“$”符号(我的意思是光标右侧(而不是左侧)的“$”,因为我将为欧元编写代码(€) 签名)。有什么想法吗?

您可以使用 UITextField 委托或收听通知,例如 UITextFieldTextDidChangeNotification
在这些方法中,检查文本并添加“$”。

因为'$'应该在正确的位置,我建议使用UITextField 属性 selectedTextRange来计算位置,然后使用setSelectedTextRange将光标移动到正确的地方。

UITextPosition * tp = [self.passwordTextField positionFromPosition:self.passwordTextField.beginningOfDocument  offset:self.passwordTextField.text.length - @"$".length];
UITextRange *sr = [self.passwordTextField textRangeFromPosition:tp toPosition:tp];

我认为 sr 是 selectedTextRange 的值。

我建议添加一个标签并将其文本设置为'$'。观察textField 的文本,当用户输入时,更新标签框架。像这样:

let label = UILabel(frame: CGRect(x: 10, y: 10, width: 30, height: 20))
label.text = "$"
label.font = contentTextField.font
label.textColor = textField.textColor
textField.superview?.addSubview(label)

textField.addTarget(self, action: "yourFunc", forControlEvents: .EditingChanged)

func yourFunc(sender:UITextField) {
    // calculate the width of sender.text
    // update the frame of label
}

实现这个 UITextField 委托方法,我认为这对你有用。

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

let currentCharacterCount = textField.text?.characters.count ?? 0

if (range.length + range.location > currentCharacterCount){
  return false
}

var cleanString: String = ""

if let text = textField.text{

  let cleanStringAry = text.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet) as NSArray

  cleanString = cleanStringAry.componentsJoinedByString("")

}

var cellAmount = 0

if cleanString.characters.count > 0{
  cellAmount = Int(cleanString)!
}

if let fff:String = string{

  if fff.characters.count > 0{

    cellAmount = cellAmount * 10 + Int(fff)!

  }else{
    cellAmount = cellAmount / 10
  }


}


let amount = NSNumber(float: Float(cellAmount)/100.0)

let currencyFormatter = NSNumberFormatter()
currencyFormatter.numberStyle = .CurrencyStyle
currencyFormatter.currencyCode = "\u{20AC}"
currencyFormatter.positiveSuffix = "\u{20AC}"
currencyFormatter.paddingPosition = .AfterSuffix
currencyFormatter.negativeSuffix = "\u{20AC}"
currencyFormatter.negativeFormat = "-¤#,##0.00"

let result = currencyFormatter.stringFromNumber(amount)
if result == "0.00\u{20AC}"{
  textField.text = ""
}else{
  textField.text = currencyFormatter.stringFromNumber(amount)

}

return false
}