Reputation: 443
I have the UITextField for currency choosing and I want to set the part of its text as non editable (in text $ 9,99 user is able to replace only 9,99). Any ideas how to do this?
Upvotes: 0
Views: 1177
Reputation: 1
You can add a target to your textField for state "editingChanged" like:
textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged)
and if length of textField becomes lower then 2 ("$ ") just set this sting into textField.text value
@objc func textFieldDidChange(_ textField: UITextField) {
guard let count = textField.text?.count else {
return
}
if count < "$ ".count
{
textField.text = "$ "
}
}
Upvotes: 0
Reputation: 1984
You need to set the textfield delegates when user start editing and characters count == 0 then append the $ sign with text field
Upvotes: 0
Reputation: 1015
you would probably want to think differently on this one. Either use separate UILabel or add LeftView with UILable as TexFields leftView for $ sign. And if you don't want to do that there is hacky way of doing it in delegate method. Whic goes like the following:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let text = (textField.text! as NSString).replacingCharacters(in: range, with: string)
return text.count > 0
}
What we are doing here is checking the text in text field when it is edited and getting the count of text characters. If the character is > 0 the textField can be edited but we are protecting if only the $ sign is remaining in the textField.
You probably would want to check which textField you want to do this, because you may have more of them and this will be used by all, so check only for that textField
Upvotes: 2
Reputation: 21
It can't be done so you will but a UIlabel for the currency sign and the sign will change automatically with localization
Upvotes: 0
Reputation: 2232
Partially editable is impossible, I think you should separate between the currency sign with the amount. Let's say you make a new UIlabel
or UItextfield
for the currency sign, then make the currency amount as a new textfield
also.
If you go with two textfields
, then you can set the currency sign which is not editable with yourTextField.enabled = false
or yourTextField.isUserInteractionEnabled = false
Upvotes: 0