25

I am trying to disable the return key found when typing in a UITextView. I want the text to have no page indents like found in a UITextField. This is the code I have so far:

- (BOOL)textView:(UITextView *)aTextView shouldChangeTextInRange:(NSRange)aRange replacementText:(NSString*)aText
{
if ([aTextView.text isEqualToString:@"\r\n"]) {
    return NO;
}

Any ideas?

5 Answers5

42

Try to use like this..

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {

    if([text isEqualToString:@"\n"])
    {
        [textView resignFirstResponder];
        return NO;
    }

    return YES;
}
Dharmbir Singh
  • 17,485
  • 5
  • 50
  • 66
  • 2
    This doesn't take into account all possible line ending characters, or the fact that a user may paste a chunk of text in one go into the text field (so not equal to "\n" but containing it) - Grzegorz's solution is much more robust. – Rupert Jul 23 '14 at 10:57
  • Just to clarify, I refer to the UITextview answer rather than the UITextField answers. – Rupert Jul 23 '14 at 11:12
20

Another solution without magic hardcoded strings will be:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:    (NSString *)text {
    if( [text rangeOfCharacterFromSet:[NSCharacterSet newlineCharacterSet]].location == NSNotFound ) {
        return YES;
    }     

    return NO;
}
Grzegorz Krukowski
  • 18,081
  • 5
  • 50
  • 71
  • 5
    +1, I like the idea of not using magic strings, which could change (they wont, but you catch my drift); It also reads easier. – Oliver Atkinson Sep 11 '13 at 06:46
13

In Swift 3+ add:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    guard text.rangeOfCharacter(from: CharacterSet.newlines) == nil else {
        // textView.resignFirstResponder() // uncomment this to close the keyboard when return key is pressed
        return false
    }

    return true
}

Don't forget to add textView's delegate in order for this to be called

Radu Ursache
  • 1,230
  • 1
  • 22
  • 35
Blake
  • 131
  • 1
  • 2
-2

I know this is late reply but this code is perfect working for me. This will disable return key initially until type any character.

textfield.enablesReturnKeyAutomatically = YES;

By Interface Builder set this property,
enter image description here

bobics
  • 2,301
  • 2
  • 23
  • 25
Ashu
  • 3,373
  • 38
  • 34
-4

why dont you change UITextView return key type like this?

enter image description here

Vaibhav Saran
  • 12,848
  • 3
  • 65
  • 75