我有一个 UITextField 的奇怪问题 - 我将它的值设置为 @"" (或其他任何原因仍然导致它),然后将字段缩小为零。下次我取消缩小它时,它显示的值与我缩小它之前的值相同,无论我是否更改了视图中的文本。在字段中键入会导致故障消失,但看起来很糟糕。
完整的代码重现:
throwaway_testViewController.h:
#import <UIKit/UIKit.h>
@interface throwaway_testViewController : UIViewController <UITextFieldDelegate>{
UITextField * unitField;
}
@property (nonatomic, assign) IBOutlet UITextField * unitField;
-(IBAction)setEditingSectionUnits;
-(void)setEditingSectionValue;
-(IBAction)equalsPress;
@end
throwaway_testViewController.m
#import "throwaway_testViewController.h"
@implementation throwaway_testViewController
@synthesize unitField;
#pragma mark - Inputs
-(IBAction)equalsPress{
[UIView animateWithDuration:0.5 animations:^(void){
[unitField setText:@""];
[self setEditingSectionValue];
}];
}
#pragma mark Input Control
-(void)setEditingSectionUnits{
[UIView animateWithDuration:0.5 animations:^(void){
CGRect newRect = unitField.frame;
newRect.size.width = 160;
unitField.frame = newRect;
}completion:^(BOOL completed){
completed ? [unitField setNeedsDisplay] : nil;
}];
[unitField becomeFirstResponder];
}
-(void)setEditingSectionValue{
[UIView animateWithDuration:0.5 animations:^(void){
CGRect newRect = unitField.frame;
newRect.size.width = [unitField.text sizeWithFont:unitField.font constrainedToSize:CGSizeMake(80, 250)].width;;
unitField.frame = newRect;
}completion:^(BOOL completed){
completed ? [unitField setNeedsDisplay] : nil;
}];
[unitField resignFirstResponder];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
[self setEditingSectionValue];
return TRUE;
}
-(void)textFieldDidBeginEditing:(UITextField *)textField{
[self setEditingSectionUnits];
}
@end
在 中xib
,放置一个UITextField
绑定到unitField
,并将文本字段的委托设置为文件的所有者。
放置一个UIButton
标签equalsPress
并将其绑定到IBAction
,另一个称为编辑,绑定到setEditingSectionUnits
。要查看重现的错误:
- 运行应用程序
- 按编辑
- 在文本字段中输入内容(最少 8-10 个字符)
- 按键盘上的输入
- 按等于按
- 按编辑
- 应该看到:光标和空文本字段
- 实际看到:无论您最后键入什么,开头都有一个光标。
- 键入会使此文本消失。