1

When user presses a button in my app I show him the alert view with an input text field there. I use the following code for that:

func addTapped(sender: UIBarButtonItem) {

    let alertController = UIAlertController(title: "", message: "Write a #name of a tag that you want to follow", preferredStyle: .Alert)

    let confirmAction = UIAlertAction(title: "Confirm", style: .Default) { (_) in
        if let field = alertController.textFields![0] as? UITextField {

            if(field.text?.characters.count > 0) {
                print("user put some data inside")
            } else {
                print("user did not put anything")
            }

        } else {
            // user did not fill field

        }
    }

    let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (_) in }

    alertController.addTextFieldWithConfigurationHandler { (textField) in
        let attributedString = NSMutableAttributedString(string: "C-TAD-")
        attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: NSMakeRange(0,6))
        textField.attributedText = attributedString
    }

    alertController.addAction(confirmAction)
    alertController.addAction(cancelAction)

    self.presentViewController(alertController, animated: true, completion: nil)

}

It works well, when user runs the app he sees:

enter image description here

but this placeholder text inside is removable. I would like to prevent that and always show this text there, so basically lock the delete option on it.

How can I lock the possibility of removing those first letters?

user3766930
  • 5,629
  • 10
  • 51
  • 104
  • FYI - this question is not specific to using `UIAlertController`. The solution is generic to using `UITextField` in any circumstance. – rmaddy Sep 15 '16 at 15:41
  • See http://stackoverflow.com/questions/19416885/add-a-permanent-character-to-uitextfield It's in Objective-C but you should be able to read it enough to get the idea. – rmaddy Sep 15 '16 at 15:42
  • @maddy, my problem is that since that textfield is inside the `UIAlertController`, I cannot make an IBOutlet to it and refer to it in the code... Therefore I don't know how to use the method `shouldChangeCharactersInRange` on it. Could you show me some example posted here as an answer? – user3766930 Sep 15 '16 at 15:48
  • Of course you can. Set the text field's delegate in the `addTextFieldWithConfigurationHandler` closure. – rmaddy Sep 15 '16 at 15:50
  • Ok so I implemented the method `func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {` in my code outside of the handler, can you tell me how can I set the delegate to it inside the handler? I tried with `textField.delegate = self` but that didn't work – user3766930 Sep 15 '16 at 15:52
  • Define "didn't work". – rmaddy Sep 15 '16 at 15:53
  • Ok @Maddy, it works now, thanks for advices. Do you bother leaving here the answer or should I remove the question? – user3766930 Sep 15 '16 at 16:02
  • I don't know Swift well enough to leave an answer. If you feel others can benefit then you should post your own answer showing how you solved the problem. – rmaddy Sep 15 '16 at 16:13

2 Answers2

1

A UITextField have a leftView and rightView that you can customise. By default the leftView is never displayed. You can add a label as the leftView or as a subview of the leftView and set the left view to Always show.

Try this code:

    let leftLabel = UILabel(frame: CGRectMake(0,0,60,21))
    leftLabel.text = "C-TAD-"
    leftLabel.textColor = .lightGrayColor()

    textField.leftView = leftLabel
    textField.leftViewMode = .Always
Carien van Zyl
  • 2,853
  • 22
  • 30
0

Following maddy's advice I was able to solve this problem. I added

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        //This makes the new text black.
        textField.typingAttributes = [NSForegroundColorAttributeName:UIColor.blackColor()]
        let protectedRange = NSMakeRange(0, 6)
        let intersection = NSIntersectionRange(protectedRange, range)
        if intersection.length > 0 {

            return false
        }
        return true
    }

method and set up a delegate to the textfield in the addTextFieldWithConfigurationHandler - that did the trick :)

user3766930
  • 5,629
  • 10
  • 51
  • 104