对象 - 如果textView为空,则禁用uibutton?

时间:2018-01-28 04:11:42

标签: ios objective-c uibutton

如果UITextView为空且下面的代码我试图禁用我的uibutton。如果字段为空,该按钮将禁用,但是,当我使用下面的内容时,如果文本视图中包含值,则按钮似乎不会“启用”?知道为什么会这样吗?

编辑/更新:我已在下面更新了我的代码(问题解决了一半)。在这种情况下,如果文本视图为空,则禁用我的发送按钮。但是,一旦我在视图中有文本并按下发送,如果我再次点击发送(并且文本视图再次为空),则不再禁用发送按钮。为什么是这样?

     - (void)viewDidLoad {

        [super viewDidLoad];

            self.sendButton.userInteractionEnabled = NO;

         }

- (void)textViewDidChange:(UITextView *)textView {
    self.sendButton.userInteractionEnabled = (textView.text.length > 0);

}

3 个答案:

答案 0 :(得分:1)

您必须实施UITextView委托:

- (void)textViewDidChange:(UITextView *)textView {
    sendButton.userInteractionEnabled = (textView.text.length > 0);
}

答案 1 :(得分:0)

执行viewDidLoad后,您必须在self.replyField中设置文本。

每当您更改self.replyField中的值时,请尝试执行以下代码:

    if (self.replyField.text.length > 0) {
        sendButton.userInteractionEnabled = YES;
    }
    else {
        sendButton.userInteractionEnabled = NO;
    }

您可以使用isEnabled而不是userInteractionEnabled

答案 2 :(得分:0)

你应该在下面的委托方法中实现根据文本值启用和禁用按钮

optional func textField(_ textField: UITextField, 
shouldChangeCharactersIn range: NSRange, 
      replacementString string: String) -> Bool {
}