Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

textview keyboard not resigning when i press done iOS

i have a textview and when i press done the textview starts a new line.

I have implemented these methods and added all the delegates

@property (nonatomic, strong) IBOutlet UITextView *textField;

-(void)textViewDidEndEditing:(UITextView *)textView //was UITextField
{
    [self.textField resignFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextView *)textField{

    [textField resignFirstResponder];
    return YES;

}

i set the keyboard return key to done in attributes inspector. i want the done key on the keyboard to resign first responder, it does not seem to work.

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

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

    // error thrown here saying code will never execute
    if(range.length + range.location > textField.text.length)
{
    return NO;
}

NSUInteger newLength = [textField.text length] + [string length] - range.length;
return newLength <= 300;
}

how can i add both statements so they will work without the error?

like image 613
smithyy Avatar asked Aug 03 '15 13:08

smithyy


2 Answers

add Delegate UITextViewDelegate

@property (nonatomic, strong) IBOutlet UITextView *textField;

Write this line in viewDidLoad

textField.delegte = self;

// Add below delegate method [code is in Swift. please find obj-c method and write logic as i have]

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

    if([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    if (textField.text.length >= 300) {
        return NO;
    }
    return YES;
}
like image 116
Chetan Prajapati Avatar answered Nov 19 '22 15:11

Chetan Prajapati


Go to your story board and then select your text field and set delegate and also confirm UITextFieldDelegate protocol in your .h file

Hope it helps.

like image 2
Pradumna Patil Avatar answered Nov 19 '22 16:11

Pradumna Patil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!