user1445205
user1445205

Reputation:

Disable return key in UITextView

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?

Upvotes: 25

Views: 16386

Answers (5)

Blake
Blake

Reputation: 131

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

Upvotes: 13

Ashu
Ashu

Reputation: 3523

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

Upvotes: -1

Grzegorz Krukowski
Grzegorz Krukowski

Reputation: 19792

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;
}

Upvotes: 20

Vaibhav Saran
Vaibhav Saran

Reputation: 12908

why dont you change UITextView return key type like this?

enter image description here

Upvotes: -4

Dharmbir Singh
Dharmbir Singh

Reputation: 17535

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;
}

Upvotes: 42

Related Questions