Instead of manually adding each TextField delegate to the UIView, like this:
self.txtName.delegate = self;
self.txtAge.delegate = self;
Is there a quicker way of adding all TextField delegates to a UIView?
Alternatively, is there a way I can obtain the position of a TextField that has just received focus, without using UITextFieldDelegate?
Create an outlet collection
@property(nonatomic, strong) IBOutletCollection(UITextField) NSArray *textFields;
then loop over the textFields
for(UITextField *aTextField in self.textFields)
{
aTextField.delegate = self;
}
There is a good post about IBOutlets on NSHipster
for (UIView *aView in self.view.subviews) {
if ([aView isKindOfClass:[UITextField class]]) {
((UITextField *)aView).delegate = self;
}
}
«Two or more: Use a for» — Edsger W. Dijkstra
[@[self.txtNames, self.txtAge] enumerateObjectsUsingBlock:^(UITextField *tf, NSUInteger idx, BOOL *stop){
tf.delegate = self;
}];
Ok: not a for. But the same principle.
If you want to use a for
, you could use Fast Enumeration instead of block-based Enumeration.
for (UITextField *tf in @[self.txtNames, self.txtAge]) {
tf.delegate = self;
}
在视图控制器头文件的末尾添加UITextFieldDelegate 。
@interface AddressesViewController : ViewController<UITextFieldDelegate>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.