我正在为我的iOS应用程序编写表单,我的UITextField
行为很奇怪:
当表单处于更新状态(字段已填满)时,我可以编辑并获取具有.text
属性的新输入文本(由用户键入)。但是当表单处于插入模式时,UITextField
s最初是空的,我无法使用.text
属性来输入文本,因为无论用户输入什么类型,它总是返回一个空字符串。
以下是显示问题的视频:https://youtu.be/tPJZ3sC-IFU
{
__weak IBOutlet UITextField *txtLibelle; //linked by ctrl + drag to the storyboard
NSString *libelleTemp;
}
- (void)viewDidLoad {
[super viewDidLoad];
// ...
[txtLibelle addTarget:self
action:@selector(editingChanged:)
forControlEvents:UIControlEventEditingChanged];
// ...
}
-(void) editingChanged:(id)sender {
libelleTemp = txtLibelle.text;
// libelleTemp is set to @"" whatever the user has typed in when I'm in insert mode
}
-(void)initWithLib:(NSString *)lib {
libelleTemp = [NSString stringWithString:lib];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
if (indexPath.section == 0) {
txtLibelle.text = libelleTemp;
}
// ...
return cell;
}
从上一个视图控制器调用initWithLib:方法,如下所示:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UIStoryboard *accueilNavSB = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
FicheAlerteTableViewController *vc = [accueilNavSB instantiateViewControllerWithIdentifier:@"ficheAlerte"];
NSString *libelle = @"";
[vc initWithLib:libelle];
[self.navigationController showViewController:vc sender:self];
}
我已经将故事板中的字段重新链接到我的班级,并且在调试模式下,我的UITextField
不是零。
我的文本字段位于静态UITableView
中,因此我可以看到更新是否有效滚动屏幕上的单元格然后滚动它。
有谁知道为什么会发生这种情况以及如何解决问题?
答案 0 :(得分:1)
您的代码中有一个错误。您没有使用正确的属性将文本加载到标签中。使用此。
这对我有用。我在Xcode上测试了这个。
-(void) editingChanged:(id)sender {
//label1.text = field.text;
libelleTemp=field.text;
NSLog(@"text is %@",libelleTemp);
// libelleTemp is set to @"" whatever the user has typed in when I'm in insert mode
}
答案 1 :(得分:0)
您正在使用UITextField,它可以使用UITextFieldDelegate来注册编辑事件等。有关详细信息,请参阅Apple的documentation。
我相信您正在寻找的方法是:
<UITextFieldDelegate> //link your textField.delegate = self
- (void)textFieldDidEndEditing:(UITextField *)textField {
libelleTemp = textField.text;
}
您可以尝试的另一件事是直接链接(IBAction)方法,而不是以编程方式设置目标。只需控制拖动即可将此方法链接到IB中的文本字段。
- (IBAction)libelleEndedEditing:(UITextField *)sender {
libelleTemp = sender.text;
}
答案 2 :(得分:0)
您使用的是错误的操作。 UITextField&#39; text&#39;只有在编辑结束后才会设置属性。因此,您需要将方法连接到&#34;编辑结束&#34; Interface Builder中的事件。