Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uneditable prefix inside a UITextField using Swift

I'm having a problem regarding the creation of a prefix inside a UITextField using the new Swift language. Currently I have created the UITextField using the Interface Builder and I have assigned an IBOutlet to it, named usernameField, then using the textFieldDidBeginEditing function I write a NSMutableAttributedString inside it, named usernamePrefix, containing only the word "C-TAD-" and finally I limited the UITextField max characters number to 13, like so:

class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet var usernameField : UITextField!

    private var usernamePrefix = NSMutableAttributedString(string: "C-TAD-")

    func textFieldDidBeginEditing(textField: UITextField) {
        if textField == usernameField {
            if usernameField.text == "" {
                usernameField.attributedText = usernamePrefix
            }
        }

        usernameField.addTarget(self, action: "textFieldDidChangeText:", forControlEvents:UIControlEvents.EditingChanged)
    }

    func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {
        let maxUsernameLength = countElements(usernameField.text!) + countElements(string!) - range.length

        return maxUsernameLength <= 13
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        usernameField.delegate = self
        passwordField.delegate = self
    }
}

Now, how can I assign new parameters to the usernamePrefix in order to have to give 2 different colors to the text written in the UITextField? I would like to have the prefix in .lightGreyColor() and the rest in .blackColor(). Also how can I make the usernamePrefix un-editable and un-deletable by the user?

Thanks for the help

like image 812
Aluminum Avatar asked Feb 10 '15 15:02

Aluminum


1 Answers

Simpler option would be to set leftView of the UITextField and customise it how you like it:

let prefix = UILabel()
prefix.text = "C-TAD-"
// set font, color etc.
prefix.sizeToFit()

usernameField.leftView = prefix
usernameField.leftViewMode = .whileEditing // or .always

It is un-editable and un-deletable and you don't need to do any calculations to check the length of the input.

like image 139
sash Avatar answered Oct 31 '22 02:10

sash