2013-02-22 29 views
0

我有一個簡單的UITextField,當有人去編輯它,並彈出鍵盤時,視圖向上移動,以便用戶可以看到他們進入的東西。但是,當我關閉鍵盤時,視圖不會回到原來的位置!我正在使用CGPoint屬性捕獲其在viewDidLoad上的原始位置,然後在鍵盤關閉時嘗試將其重新設置爲該位置。UIView在動畫後沒有回到正確的位置

代碼:

- (void)viewDidLoad { 

    [super viewDidLoad]; 

    // Set the original center point for shifting the view 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil]; 
    self.originalCenter = self.view.center; 
} 

- (void)doneWithNumberPad { 

    [locationRadius resignFirstResponder]; 

    [UIView beginAnimations:nil context:NULL]; 
    [UIView setAnimationDuration:0.25]; 
    self.view.center = self.originalCenter; 
    [UIView commitAnimations]; 
} 

- (void)keyboardDidShow:(NSNotification *)note 
{ 
    [UIView beginAnimations:nil context:NULL]; 
    [UIView setAnimationDuration:0.25]; 
    self.view.center = CGPointMake(self.originalCenter.x, 150); 
    [UIView commitAnimations]; 
} 

回答

1

viewDidLoad被調用時,您的視圖層次結構尚未針對當前設備的屏幕尺寸或方向佈局。現在看self.view.center爲時尚早。

而不是viewDidLayoutSubviews

- (void)viewDidLayoutSubviews { 
    [super viewDidLayoutSubviews]; 
    self.originalCenter = self.view.center; 
} 

請注意,如果您支持自動旋轉,即使自動旋轉發生時鍵盤可見,即使這樣也無法正常工作。

+0

好東西我不支持自動旋轉! – 2013-02-22 21:34:40

0

如果你不需要一個絕對的最終中心位置,一個可靠的方式來實現它的作用是當鍵盤顯示並按照固定值向下移動時,將視圖向上移動一個固定值當鍵盤隱藏時。

#define OFFSET 100 

- (void)doneWithNumberPad { 
    [locationRadius resignFirstResponder]; 

    [UIView beginAnimations:nil context:NULL]; 
    [UIView setAnimationDuration:0.25]; 
    self.view.center = CGPointMake(self.view.center.x, self.view.center.y + OFFSET); 
    [UIView commitAnimations]; 
} 

- (void)keyboardDidShow:(NSNotification *)note 
{ 
    [UIView beginAnimations:nil context:NULL]; 
    [UIView setAnimationDuration:0.25]; 
    self.view.center = CGPointMake(self.view.center.x, self.view.center.y - OFFSET); 
    [UIView commitAnimations]; 
} 
相關問題