1

For example, a UITextField cannot be its own delegate, but is it OK to just have it register itself as an observer of its own notifications? Looks weird but seems to work fine. Thoughts?

// MyTextField.h

@interface MyTextField : UITextField
@end

// MyTextField.m

@interface MyTextField ()
- (void)myTextFieldDidChange:(NSNotification *)notification;
@end

@implementation MyTextField

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [[NSNotificationCenter defaultCenter]
         addObserver:self
         selector:@selector(myTextFieldDidChange:)
         name:UITextFieldTextDidChangeNotification
         object:self];
    }
}

- (void)myTextFieldDidChange:(NSNotification *)notification {
    // Do custom stuff here.
}

@end
4

1 回答 1

1

你正在做的似乎很好,但对于这个特定的例子有一个更纯粹的解决方案:

// MyTextField.h

@interface MyTextField : UITextField
@end

// MyTextField.m

@interface MyTextField ()
- (void)myTextFieldDidChange:(UITextField *)textField;
@end

@implementation MyTextField

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self addTarget:self action:@selector(myTextFieldDidChange:)
       forControlEvents:UIControlEventEditingChanged];
    }
    return self;
}

- (void)myTextFieldDidChange:(MyTextField *)myTextField {
    // Do custom stuff here.
}

@end

查看UIControlEvents参考

于 2011-11-04T02:47:05.150 回答