这是我如何成功完成此操作的示例。我只对阻止输入某些字符感兴趣,所以我只实现textView:shouldChangeTextInRange:replacementText:
然后传递其余的。
#import "INFTextView.h"
@interface INFTextView () <UITextViewDelegate>
@property (nonatomic, weak) id<UITextViewDelegate> externalDelegate;
@end
@implementation INFTextView
- (id)init {
self = [super init];
if (!self) {
return nil;
}
self.delegate = self;
return self;
}
- (void)awakeFromNib {
self.delegate = self;
}
- (void)setDelegate:(id<UITextViewDelegate>)delegate {
// we always want self to be the delegate, if someone is interested in delegate calls we will forward those on if applicable
if (delegate == self) {
[super setDelegate:self];
return;
} else {
// capture that someone else is interested in delegate calls
_externalDelegate = delegate;
}
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
NSCharacterSet *unsupportedCharacterSet = [[NSCharacterSet characterSetWithCharactersInString:kINFSupportedCharacters] invertedSet];
NSRange unsupportedCharacterRange = [text rangeOfCharacterFromSet:unsupportedCharacterSet];
if (unsupportedCharacterRange.location == NSNotFound) {
return YES;
} else {
return NO;
}
}
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
if ([_externalDelegate respondsToSelector:@selector(textViewShouldBeginEditing:)]) {
return [_externalDelegate textViewShouldBeginEditing:textView];
}
return YES;
}
- (BOOL)textViewShouldEndEditing:(UITextView *)textView {
if ([_externalDelegate respondsToSelector:@selector(textViewShouldEndEditing:)]) {
return [_externalDelegate textViewShouldEndEditing:textView];
}
return YES;
}
- (void)textViewDidBeginEditing:(UITextView *)textView {
if ([_externalDelegate respondsToSelector:@selector(textViewDidBeginEditing:)]) {
[_externalDelegate textViewDidBeginEditing:textView];
}
}
- (void)textViewDidEndEditing:(UITextView *)textView {
if ([_externalDelegate respondsToSelector:@selector(textViewDidEndEditing:)]) {
[_externalDelegate textViewDidEndEditing:textView];
}
}
- (void)textViewDidChange:(UITextView *)textView {
if ([_externalDelegate respondsToSelector:@selector(textViewDidChange:)]) {
[_externalDelegate textViewDidChange:textView];
}
}
- (void)textViewDidChangeSelection:(UITextView *)textView {
if ([_externalDelegate respondsToSelector:@selector(textViewDidChangeSelection:)]) {
[_externalDelegate textViewDidChangeSelection:textView];
}
}
@end
导致我提出这个问题的一个大“问题”是我试图覆盖delegate
返回_externalDelegate
,但这会导致一些奇怪的副作用(必须有内部代码取决于要返回的实际委托)。