我正在尝试在文本字段的开头添加$符号。如果字符数为1,则$ sign不会被隐藏,但如果字符数为零,则隐藏$符号并显示占位符文本。我有代码,但它无法正常工作。它不会显示$符号。你能帮我么。这是下面的代码。
override func viewDidLoad() {
super.viewDidLoad()
self.Price.delegate = self
didChangeText()
}
var amount: String {
get {
if self._amount.characters.count > 1 {
return (self._amount as NSString).substring(from: 2)
}
return ""
}
}
// MARK: - UITextField Observing
private var newVal: String = ""
private var _amount: String = ""
func didChangeText() {
if ((Price.text?.characters.count)! > 2) {
if Price.text?.range(of: "$ ") == nil {
Price.text = newVal
}
}
if ((Price.text?.characters.count)! == 1) && ((Price.text?.characters.count)! > newVal.characters.count) {
Price.text = "$ " + Price.text!
}
if ((Price.text?.characters.count)! == 2) && ((Price.text?.characters.count)! < newVal.characters.count) {
Price.text = ""
}
newVal = Price.text ?? ""
_amount = newVal
}
答案 0 :(得分:0)
请尝试以下操作:
let priceField = UITextField(frame: CGRect(x: 0.0, y: 0.0, width: 100.0, height: 30.0))
let leftDollarSymbol = UILabel(frame: CGRect(x: 0.0, y: 0.0, width: 15.0, height: 30.0))
leftDollarSymbol.textAlignment = .center
leftDollarSymbol.text = "$"
priceField.leftView = leftDollarSymbol
根据您的需要更新leftDollarSymbol或设置leftview nil