4

我正在使用半透明導航欄和狀態欄,並且我的視圖控制器想要全屏。因此,我的視圖控制器的視圖在導航欄和狀態欄下展開並佔用屏幕的全部大小。在實際旋轉之前確定導航欄的新框架 - iOS

我也有一個標籤,我想直接在導航欄下對齊。因爲我無法在標籤和導航欄之間直接添加約束,所以我在標籤頂部和父視圖頂部之間添加了約束條件。我將contstraint的常量設置爲等於狀態欄的高度+導航欄的高度。

我的問題是在縱向和橫向之間旋轉,因爲導航欄的高度發生變化,我需要我的標籤也很好地旋轉,所以我需要知道導航欄的新高度willRotateToInterfaceOrientation:方法。

我使用此方法確保當視圖控制器從縱向或橫向導航到時,標籤位於正確的位置。它工作正常。

- (void)viewWillAppear:(BOOL)animated 
{ 
    [super viewWillAppear:animated]; 

    // Get Y origin for Label 
    CGFloat navBarY = self.navigationController.navigationBar.frame.origin.y; 
    CGFloat navBarHeight = self.navigationController.navigationBar.frame.size.height; 
    CGFloat labelY = navBarY + navBarHeight; 

    // Set vertical space constraint for Label 
    self.labelConstraint.constant = labelY; 
} 

當導航欄高度從44px變爲32px時,我使用此方法重新定位標籤的方向。問題是,我需要獲得導航欄在旋轉之後的實際發生旋轉之前的NEW高度。

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration 
{ 
    [super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration]; 

    // Get Y origin for Label 
    CGFloat navBarY = self.navigationController.navigationBar.frame.origin.y; 
    CGFloat navBarHeight = self.navigationController.navigationBar.frame.size.height; 
    CGFloat labelY = navBarY + navBarHeight; 


    // This obviously returns the the current Y origin for label before the rotation 
    // Which isn't very useful. 

    NSLog(@"labelY: %f", labelY); 


    // This code produces the desired effect, but obviously I want to avoid 
    // hard-coding the values. 

    if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation)) { 
     self.labelConstraint.constant = 20 + 32; 
    } else { 
     self.labelConstraint.constant = 20 + 44; 
    } 
} 

爲了好玩,我試圖設置Y原點爲didRotateFromInterfaceOrientation:旋轉後的標籤,但預計它的不順暢和標籤卡入到位轉動完成後。

預先感謝您的幫助!

+0

您是否找到了解決此問題的答案? –

+0

我遇到了同樣的問題...任何解決方案? –

回答

0

答案是:Size Classes。你可以通知你自己,這是由蘋果公司充分記錄。您將不得不使用此功能:func willTransitionToTraitCollection(newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator)。設置視圖時,我會建議在視圖控制器中添加兩個屬性,一個爲NSLayoutConstraint,一個用於肖像模式,一個用於橫向。自iOS 8以來,可以一次激活/停用多個約束。在上面提到的功能,請執行下列操作:

if newCollection.verticalSizeClass == .Compact { //orientiation is landscape 
    NSLayoutConstraint.deactivateConstraints(self.portraitConstraints) 
    NSLayoutConstraint.activateConstraints(self.landscapeConstraints) 
} else { 
    NSLayoutConstraint.deactivateConstraints(self.landscapeConstraints) 
    NSLayoutConstraint.activateConstraints(self.portraitConstraints) 
} 

請務必先停用,否則你的約束將發生衝突。

對不起,「swifty」的答案,我想你可以把它翻譯成ObjC。如果您有任何問題,請隨時詢問。