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 
+1

您正在將視圖轉變爲控制器,但是如果它起作用,它就會起作用。爲了更好的MVC,讓包含文本字段的ViewController成爲委託。 –

+0

但是,上面的方法保持了視圖控制器的清潔,並允許'MyTextField'在其他視圖控制器中被重用,而不必以完全相同的方式重新實現'textFieldDidChange:'功能。 – ma11hew28

回答

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 reference