Reputation: 15
I am trying to make a custom TextField (KSTextField). I inherited my text field from UITextField. As you can see my KSTextField.h file below.
#import <UIKit/UIKit.h>
#import <UIKit/UITextField.h>
@interface KSTextField : UITextField {}
@end
In my KSTextField.m i tried to set a dummy text attribute. But it doesn't work. Is super.text usage wrong?
My main purpose is, making a custom UITextField that only allows for upper case characters which is needed for my project.
#import "KSTextField.h"
@implementation KSTextField
- (id)init {
self = [super init];
super.text = @"help";
return self;
}
- (void)textFieldDidChangeForKS:(KSTextField *)textField {
self.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters;
NSString *textToUpper = [textField.text uppercaseString];
[self setText:textToUpper];
}
@end
And also mine ViewController.h is below
#import <UIKit/UIKit.h>
#import "KSTextField.h"
@interface ViewController : UIViewController
@property (nonatomic, copy) IBOutlet KSTextField *txtKsName;
@end
Here's my ViewController.m which i want to set my KSTextField.text
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.txtKsName = [[KSTextField alloc] init];
}
Delegate events do not solve my issue. Because i'll add much more features later. It will be my custom textfield thanks!
Upvotes: 1
Views: 573
Reputation: 10994
The answer is: you're doing it wrong! You don't have to subclass to allow uppercase characters only. Use a UITextFieldDelegate
:
Using the textField:shouldChangeCharactersInRange:replacementString:
method, you can say whether on not the character typed is allowed to be added to the box.
Try something like this:
- (BOOL)textField:(UITextField *)field shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)characters
{
NSCharacterSet *blockedCharacters = [[[NSCharacterSet uppercaseLetterCharacterSet] invertedSet] retain];
return ([characters rangeOfCharacterFromSet:blockedCharacters].location == NSNotFound);
}
Upvotes: 2