highlighting the text inside the textfield

4.7k views Asked by At

I want the text inside the textfield to be highlighted when I tap on it.

I want the original text to be deleted the moment someone tap on the numberpad. I tried using clearButtonMode but then since my textfield size is very small the cross icon fully occupy the textfield.

Any idea how to achieve this?

5

There are 5 answers

0
Abhinav On BEST ANSWER

This can be achieved by

(void)textFieldDidBeginEditing:(UITextField *)iTextField {
    [iTextField selectAll:self];
}
2
Bogatyr On

You need to do the highlight yourself. You could try:

  • changing the font of the text field (larger, bolder, different color)
  • overlaying a transparent UIView on top of the text field.
  • changing the background of the text field
  • change the border style

there are many options...

EDIT: in response to your question, in order to clear the field of the previous value whenever editing begins in your text field, you set up your object to conform to the UITextFieldDelegate protocol, and implement this method:

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    textField.text = nil;
}
0
Jonas On

If you still want to be able to use other delegate functions in you ViewController, I recommend you to add this:

override weak var delegate: UITextFieldDelegate? {
    didSet {
        if delegate?.isKindOfClass(YourTextField) == false {
            // Checks so YourTextField (self) doesn't set the textFieldDelegate when assigning self.delegate = self 
            textFieldDelegate = delegate
            delegate = self
        }
    }
}

// This delegate will actually be your public delegate to the view controller which will be called in your overwritten functions
private weak var textFieldDelegate: UITextFieldDelegate?

class YourTextField: UITextField, UITextFieldDelegate {

    init(){
        super.init(frame: CGRectZero)
        self.delegate = self
    }

    func textFieldDidBeginEditing(textField: UITextField) {
        textField.performSelector(Selector("selectAll:"), withObject: textField)
        textFieldDelegate?.textFieldDidBeginEditing?(textField)
    }
}

This way your view controller doesn't need to know that you have overwritted the delegate and you can implement UITextFieldDelegate functions in your view controller.

let yourTextField = YourTextField()
yourTextField.delegate = self
2
Craig Miller On

The easiest way to highlight the text on tapping of the text field is simply to subclass UITextField, override becomeFirstResponder and select all text in there.

0
Matjan On

If Select All: doesn't always work here's a fix:

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [textField performSelector:@selector(selectAll:) withObject:textField afterDelay:0.f];
}