根据 UISwitch 位置更改 UITextView 的行为

Change behavior of a UITextView according to UISwitch position

我有一个 UITextView,我在其中附加了委托协议 textViewDidChange 以执行不同的操作。

现在我只想在我的 UISwitch 为 "ON" 时附加此委托方法。我该怎么做?

谢谢

在您的委托方法中,您可以将所有代码放在一个 if 语句中,即 if switch.on {...。如果开关的 on 属性 设置为 true,它将执行您的其余代码。否则它会跳过它。

听起来您希望 textViewDidChange: 仅在开关打开时触发。否则,它不应该开火。

我不建议设置和取消设置委托来完成此操作。

相反,您可以退出该方法:

- (void)textViewDidChangeSelection:(UITextView *)textView {
    if (!self.switch.isOn) {
        return; // bail out
    }
    // your "different actions" code
}

或者,根据您的风格,您可以执行以下操作:

- (void)textViewDidChangeSelection:(UITextView *)textView {
    if ([self shouldRespondToChangeInTextView:textView])
        [self respondToChangeInTextView:textView];
    }
}

- (BOOL)shouldRespondToChangeInTextView:(UITextView *)textview {
    return self.switch.isOn;
}

- (void)respondToChangeInTextView:textView:(UITextView *)textView {
    // your "different actions" code
}