2012-11-04 16 views
0

我有一个特殊问题。我有两个宽度为280px的UITextFields。焦点,我希望他们能够缩短露出一个按钮 - 我做了下面的代码:UITextField不会更改Refocus上的帧

- (void)textFieldDidBeginEditing:(UITextField *)textField 
{ 
    CGRect revealButton = CGRectMake(textField.frame.origin.x, textField.frame.origin.y, 221, textField.frame.size.height); 

    [UIView beginAnimations:nil context:nil]; 
    textField.frame = revealButton; 
    [UIView commitAnimations]; 
    NSLog(@"%f",textField.frame.size.width); 
} 

一旦编辑结束,他们应该回到他们原来的框架:

- (void)textFieldDidEndEditing:(UITextField *)textField 
{ 
    CGRect hideButton = CGRectMake(textField.frame.origin.x, textField.frame.origin.y, 280, textField.frame.size.height); 

    [UIView beginAnimations:nil context:nil]; 
    textField.frame = hideButton; 
    [UIView commitAnimations]; 
} 

我第一次关注文本字段时,它完美地工作。但是,如果我在聚焦其他内容之后将焦点放在第一个文本字段上(例如,如果我最初将第一个文本字段对焦,然后将焦点放在第一个文本字段上,然后重新聚焦第一个文本字段,或者如果我最初将焦点对准第一个文本字段,它根本不会改变其框架。更令人费解的是它的作为它的宽度 - 它只是不会显示在屏幕上。此外,这个问题不适用于第二个文本字段。

任何想法?在此先感谢...

回答

1

这很奇怪,我跑了一个快速测试使用两个文本字段具有完全相同的代码,并每次工作。

我建议删除文本字段和连接并重建它们。清理所有目标并重试。

根据您的意见编辑:

如果您使用自动布局,你不能直接修改的文本字段的帧。系统计算UI元素的实际框架。

为了您的目的,我建议为每个文本字段设置一个宽度约束。确保只有左边的右间距约束不能同时包含宽度约束。动画它使用下面的代码:

- (NSLayoutConstraint *)widthConstraintForView:(UIView *)view 
{ 
    NSLayoutConstraint *widthConstraint = nil; 

    for (NSLayoutConstraint *constraint in textField.constraints) 
    { 
     if (constraint.firstAttribute == NSLayoutAttributeWidth) 
      widthConstraint = constraint; 
    } 

    return widthConstraint; 
} 

- (void)animateConstraint:(NSLayoutConstraint *)constraint toNewConstant:(float)newConstant withDuration:(float)duration 
{ 
    [self.view layoutIfNeeded]; 
    [UIView animateWithDuration:duration animations:^{ 
     constraint.constant = newConstant; 
     [self.view layoutIfNeeded]; 
    }]; 
} 


- (void)textFieldDidBeginEditing:(UITextField *)textField 
{ 
    float newWidth = 221.0f; 

    NSLayoutConstraint *widthConstraint = [self widthConstraintForView:textField]; 

    [self animateConstraint:widthConstraint toNewConstant:newWidth withDuration:0.5f]; 
} 

- (void)textFieldDidEndEditing:(UITextField *)textField 
{ 
    float newWidth = 280.0f; 

    NSLayoutConstraint *widthConstraint = [self widthConstraintForView:textField]; 

    [self animateConstraint:widthConstraint toNewConstant:newWidth withDuration:0.5f]; 
} 
+0

呀 - 事实是,这是我的工作能自动布局之前......起初我还以为是与约束的问题,但第一个文本字段作品如果它是第一个被聚焦的话,那就完美了...... – gtmtg

+1

如果使用自动布局,则不能通过更改其框架来更改文本字段的大小。例如,您可以设置一个宽度约束并修改它。 – Tobi

+0

虽然在第一个焦点...... – gtmtg