【问题标题】:Enable save button using shouldChangeTextInRange使用 shouldChangeTextIn Range 启用保存按钮
【发布时间】:2015-10-30 23:13:13
【问题描述】:

我正在尝试创建一个保存按钮,当用户在 TextViewTextField 中输入文本时,该按钮将启用。

我为按钮创建了一个名为“saveButton”的IBOutlet

使用以下代码,保存按钮永远不会启用。

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

【问题讨论】:

  • 是否曾经调用过UITextViewDelegateUITextFieldDelegate 方法?
  • 是的,它们是 - 两个代表都在头文件中声明
  • enableSaveButtonForQuote:author: 方法是否被调用过?
  • 你不要在 shouldchangechatracters 方法中简单地启用=yes
  • 使用调试器。验证您希望调用的所有方法实际上都在调用。验证各种值是否具有您期望它们具有的值。然后使用相关详细信息更新您的问题。没有人可以回答您的问题,因为您还没有告诉我们发布的代码实际发生了什么。

标签: ios objective-c uinavigationbar


【解决方案1】:

您可以简单地使用布尔值来实现这一点

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

【讨论】:

    【解决方案2】:

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

    还要确保设置了 textField 和 textView 的委托。

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

    【讨论】:

    • 好的,两个 IBOutlets 的委托都设置为包含 textField 和 textView 的 viewController,但它仍然无法正常工作...
    • @Alexander 是的,您确实需要在委托方法中初始化字符串。当YESshouldChangeText 方法返回时,您将如何确定更改后的文本是什么?
    • @rmaddy 抱歉,我忘记了委托方法返回 true 后 text 属性发生了变化。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-20
    • 1970-01-01
    • 2011-03-13
    • 2016-04-25
    相关资源
    最近更新 更多