1
예를 들어, a UITextField
cannot be its own delegate이지만 자체 알림의 옵저버로 등록하면 되나요? 이상하게 보이지만 잘 작동하는 것 같습니다. 생각? 당신이 무슨 일을하는지개체가 자체 알림을 구독 할 수 있습니까?
// 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
보기를 컨트롤러로 바꾸고 있지만 작동하면보기가 작동합니다. MVC를 향상 시키려면 텍스트 필드를 포함하는 ViewController를 대리자로 지정하십시오. –
그러나 위의 메서드는보기 컨트롤러를보다 깨끗하게 유지하고 정확히 같은 방식으로'textFieldDidChange : '기능을 다시 구현하지 않고도 다른보기 컨트롤러에서'MyTextField'를 다시 사용할 수 있습니다. – ma11hew28