简体   繁体   中英

Adding custom protocol to UITextField

I have some forms for the authentications and signup views and I want that all UITextField inside those forms have a UIButton as an accessory view, just above the keyboard. I want to have the possibility to set the title and the action for this button

Because I want all those text field have one and each will have a title and an action, and to avoid redundancy, I thought about a protocol. I want something like extending a custom protocol, for example UITextFieldAccessoryViewDelegate and to be conform to some functions like : -buttonAccessoryView title ... -> String -didClickOnAccessoryViewButton.. -> ()

My mind is closed. Someone can give me some ideas to do what I want ?

You could use associated objects to solve this problem. This lets you add a property and its synthesized getter/setters.

@interface UITextField(AccessoryButton)

@property(readwrite, strong, nonatomic) UIButton *accessoryButton;

@end

#import<objc/runtime.h>
@implementation UITextField(AccessoryButton)

-(UIButton*) accessoryButton
{
    objc_getAssociatedObject(self, @selector(accessoryButton));
}

-(void) setAccessoryButton:(UIButton *)accessoryButton
{
    objc_setAssociatedObject(self, @selector(accessoryButton), accessoryButton, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

Include this category into your forms that need the UIButton for the text fields. Then assign action and title to a UIButton like how you normally do.

Considering everything you want to do I think you are better off using a subclass of UITextField rather than an extension.

Extensions can't add instance variables to the objects they extend, but subclasses can. As lead_the_zeppelin points out in his answer, you can use associated objects to simulate adding instance variables with an extension but it seems like you're making it needlessly complicated when a subclass gives you everything you want.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM