I'd like to create a text field which uses the number pad and accepts only numbers, even when pasted. Currently, I have a header as such:
#import <UIKit/UIKit.h>
@interface DRPNumberTextField : UITextField <UITextFieldDelegate>
@end
Run Code Online (Sandbox Code Playgroud)
and an implementation:
#import "DRPNumberTextField.h"
@implementation DRPNumberTextField
- (id) initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
self.delegate = self;
[self setKeyboardType:UIKeyboardTypeNumberPad];
}
return self;
}
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if ([string rangeOfCharacterFromSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]].location != NSNotFound)
{
return NO;
}
return YES;
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
@end
Run Code Online (Sandbox Code Playgroud)
I've set the text fields to use this class in the storyboard. However, my desired functionality does not occur. Moreover, as determined by debugging, initWithFrame: is never called. Any ideas? As more context, these text fields are embedded inside table cells of a table view of a table view controller. Of these, I provide a custom implementation of the table view controller here:
@interface DRPImplementSettingsViewController ()
@end
@implementation DRPImplementSettingsViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
@end
Run Code Online (Sandbox Code Playgroud)
Thus it really has no implemented functionality beyond the stock. Its header is the obvious one.
EDIT: As some have pointed out, I don't need to subclass the text field to implement delegate functionality. I can put that elsewhere. But my question is this: why doesn't what I've presented here work? I can't find my mistake.
You need also override - (id)initWithCoder:(NSCoder *)decoder in your DRPNumberTextField. if you are using the custom UITextField in XIB or storyboard, initWithFrame: will not be called, initWithCoder: is called instead.
| 归档时间: |
|
| 查看次数: |
4957 次 |
| 最近记录: |