你好我在这里搜索了很多关于使用shouldChangeCharactersInRange子类化uitextfield来处理最大长度的帖子。
尝试了以下线程,但仍无效: - How properly subclass UITextField in iOS? - UITextField shouldChangeCharactersInRange Delegate not working - Set custom UITextField max length
我的代码如下所示。
·H
//UITextFieldGeneral.h
#import <UIKit/UIKit.h>
@interface UITextFieldGeneral : UITextField <UITextFieldDelegate>{
int maxLength;
}
-(void)inisialisasi:(int)maxValue;
@end
的.m
//UITextFieldGeneral.m
#import "UITextFieldGeneral.h"
@implementation UITextFieldGeneral
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
// self.delegate = self;
}
return self;
}
-(void)inisialisasi:(int)maxValue{
// self.keyboardType = UIKeyboardTypeDecimalPad;
self.textColor = [UIColor blackColor];
self.font = [UIFont fontWithName:fontname size:fontSizeH3];
self.tintColor = [UIColor blackColor];
[self setBackgroundColor:[UIColor whiteColor]];
[self setBorderStyle:UITextBorderStyleRoundedRect];
[self setTextAlignment:NSTextAlignmentRight];
maxLength = maxValue;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString*)string{
if (range.location >= maxLength)
return NO;
return YES;
}
viewcontroller中的代码
·H
@interface TransferInternDaftarRekViewController : TableViewControllerCustomForInput<UITextFieldDelegate>{
的.m
tfBerita = [[UITextFieldGeneral alloc] initWithFrame:(CGRect){xLbl+widthLbl+20,5,widthLbl,30}];
tfBerita.keyboardType = UIKeyboardTypeDefault;
[tfBerita inisialisasi:20];
//tfBerita.delegate = tfBerita;
tfBerita.delegate = self;
不会调用theChangeCharactersInRange方法,但是如果我改变了tfBerita.delegate = self; to tfBerita.delegate = tfBerita;输入3个字符后给我一个错误。
我错过了什么吗?