0

I'm having a peculiar problem. I have a view with two UITextFields that start out 280px wide. On focus, I want them to shorten to reveal a button - I'm doing that with the following code:

- (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);
}

Once editing has ended, they should go back to their original frame:

- (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];
}

The first time I focus a text field, it works perfectly. However, if I focus the first text field after focusing something else (for example, if I focus the first text field initially, focus the second, and then refocus the first, or if I initially focus the second and then focus the first), it simply won't change its frame. Even more puzzling is the fact that it will log 221 as its width - it just won't show that on the screen. Furthermore, this problem doesn't apply to the second text field.

Any ideas? Thanks in advance...

4

1 回答 1

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];
}
于 2012-11-04T20:17:41.580 回答