UITextField如何使.text始终显示' $'在右侧键入数字时签名?

时间:2016-03-17 02:46:51

标签: ios swift uitextfield ios9

我有一个UITextField,而且我正在接受一些输入,这些都是美元。我需要实现如何始终出现' $'我输入数字后的标志(我的意思是我的光标右边(不是左边)的'' $''因为我将写欧元(€)标志的代码为好)。有什么想法吗?

3 个答案:

答案 0 :(得分:0)

您可以使用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的值。

答案 1 :(得分:0)

实现这个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
}

答案 2 :(得分:-1)

我建议添加标签并将其文本设置为'$'。观察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
}