2016-02-26 34 views
0

我正在創建一個iPhone應用程序,其中包含帶有文本標籤的圖標。我希望手機旋轉到橫向模式時隱藏標籤,因爲它們沒有足夠的空間。什麼是最簡單的方法來做到這一點?手機處於橫向模式時隱藏標籤

回答

1

您可以先在viewDidLoad中添加一個NSNotification以瞭解設備的方向更改。

NSNotificationCenter.defaultCenter().addObserver(self, selector: "rotated", name: UIDeviceOrientationDidChangeNotification, object: nil) 

這將調用函數「旋轉」時,設備知道它的方向改變了,那麼你只需要創建一個函數,並把我們的代碼裏面。

func rotated() 
{ 
    if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation)) 
    {    
     print("landscape") 
     label.hidden = true 
    } 

    if(UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation)) 
    { 
     print("Portrait") 
     label.hidden = false 
    } 

} 

解決方案從"IOS8 Swift: How to detect orientation change?"

+0

完美工作,謝謝! –

+0

不客氣:) – Lee

1

得到,如果你想進行動畫處理的變化(例如淡出的標籤,或其他一些動畫),實際上你可以做到這一點與通過重寫viewWillTransitionToSize方法旋轉同步例如

override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { 

coordinator.animateAlongsideTransition({ (UIViewControllerTransitionCoordinatorContext) -> Void in 

    let orient = UIApplication.sharedApplication().statusBarOrientation 

    switch orient { 
    case .Portrait: 
     println("Portrait") 
     // Show the label here... 
    default: 
     println("Anything But Portrait e.g. probably landscape") 
     // Hide the label here... 
    } 

    }, completion: { (UIViewControllerTransitionCoordinatorContext) -> Void in 
     println("rotation completed") 
}) 

super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) 
} 

以上內容來自於以下的答案必須採取的代碼示例:https://stackoverflow.com/a/28958796/994976

0

目標C版

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)orientation duration:(NSTimeInterval)duration 
{ 
    if (UIInterfaceOrientationIsPortrait(orientation)) 
    { 
     // Show the label here... 
    } 
    else 
    { 
     // Hide the label here... 
    } 
} 

斯威夫特版本

override func willAnimateRotationToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) 
{ 
    if (UIInterfaceOrientationIsPortrait(toInterfaceOrientation)) 
    { 
     // Show the label here... 
    } 
    else 
    { 
     // Hide the label here... 
    } 
} 
相關問題