2012-11-04 15 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