Sai*_*een 0 objective-c uitextfield ios
好吧标题说它主要是:
是否有准备好的UITextField组件可以在标签中采用数字(最大文本长度)?如果也可以显示数字也会很酷.
那里有组件吗?
我想拥有什么:
看到我的其他答案为一个好的子类INSTEAD.
我在TextField中添加了一个UILabel子视图来显示字符限制.
它将:
*通过自定义文本长度限制输入
*在UITextField内的UILabel子视图中显示字符限制.
*粘贴预防
结果:
要么

@implementation ViewController
@synthesize textField1;
UILabel *yourLabel;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
yourLabel = [[UILabel alloc] initWithFrame:CGRectMake(textField1.bounds.size.width-18, 12, 300, 20)];//Change your size, you will need to experiment with the size
[yourLabel setTextColor:[UIColor redColor]];
[yourLabel setBackgroundColor:[UIColor clearColor]];
[yourLabel setFont:[UIFont fontWithName: @"Trebuchet MS" size: 14.0f]];
[yourLabel setText:@""];
[textField1 addSubview:yourLabel];
textField1.delegate=self;
[self textField:textField1 shouldChangeCharactersInRange:NSMakeRange(0, 0) replacementString:@""];//To change the limit label
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
int MAXLENGTH=20;
NSString *newText = [textField.text stringByReplacingCharactersInRange:range withString:string];
if(newText.length>MAXLENGTH) {
return NO;
}
[yourLabel setText:[NSString stringWithFormat:@"%lu",MAXLENGTH-newText.length]];
return YES;
}
Run Code Online (Sandbox Code Playgroud)
我希望这符合您的需求并让您入门.
别忘了订阅UITextFieldDelegate.在.h文件中,声明:
@interface ViewController : UIViewController<UITextFieldDelegate>// -- < UITextFieldDelegate
Run Code Online (Sandbox Code Playgroud)
我创建了这个 UITextFieldLimit子类:
抓住UITextFieldLimit.h并UITextFieldLimit.m从该GitHub的仓库:
https://github.com/JonathanGurebo/UITextFieldLimit
并开始测试!
标记您的故事板创建的UITextField并使用Identity Inspector将其链接到我的子类:

然后,您可以将其链接到IBOutlet并设置限制(默认值为10).
您的ViewController.h文件应包含:(如果您不想修改设置,如限制)
#import "UITextFieldLimit.h"
/.../
@property (weak, nonatomic) IBOutlet UITextFieldLimit *textFieldLimit; // <--Your IBOutlet
Run Code Online (Sandbox Code Playgroud)
你的ViewController.m文件应该@synthesize textFieldLimit.
在ViewController.m文件中设置文本长度限制:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[textFieldLimit setLimit:25];// <-- and you won't be able to put more than 25 characters in the TextField.
}
Run Code Online (Sandbox Code Playgroud)
希望全班同学帮助你.祝好运!
| 归档时间: |
|
| 查看次数: |
1631 次 |
| 最近记录: |