Enable save button using shouldChangeTextInRange

时间:2015-10-30 23:13:14

标签: ios objective-c uinavigationbar

I am trying to create a save button which becomes enabled when the user enters text into both a TextView and a TextField.

I have a IBOutlet called 'saveButton' created for the button.

With the following code, the save button never becomes enabled.

- (void) enableSaveButtonForQuote: (NSString *) quoteText author: (NSString *) authorText {

self.saveButton.enabled = (quoteText.length > 0 && authorText > 0);
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:
(NSRange)range replacementText:(NSString *)text
{
   NSString *changedString = [textView.testringByReplacingCharactersInRange:
range withString: text];

[self enableSaveButtonForQuote: changedString author: 
self.authorTextField.text];    
return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:
(NSRange)range replacementString:(NSString *)string
{
NSString *changedString = [textField.text stringByReplacingCharactersInRange:
range withString: string];

[self enableSaveButtonForQuote:self.quoteTextView.text author:changedString];
return YES;
}

2 个答案:

答案 0 :(得分:0)

You can simply use bool value to make this happen - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange: (NSRange)range replacementText:(NSString *)text { //lets say you enter text first into textview textViewBoolValue=YES; if(textViewBoolValue && textFieldBoolValue ){ button.enabled=YES } return YES; } - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange: (NSRange)range replacementString:(NSString *)string { textFieldBoolValue=YES; if(textViewBoolValue && textFieldBoolValue ){ button.enabled=YES } return YES; }

答案 1 :(得分:0)

您忘记在enableSaveButtonForQuote方法中检查authorText的length属性。

还要确保设置了textField和textView的代理。

此外,您不需要在每个委托方法中初始化另一个字符串对象。您已经通过类变量引用了textfield / textView。你应该只使用那些文本。