2016-02-26 4 views
0

Я создаю приложение iPhone, в котором есть значки с текстовыми надписями внизу. Я хочу, чтобы метки были скрыты, когда телефон повернут в альбомный режим, поскольку для них недостаточно места. Каков самый простой способ сделать это?Скрытие ярлыка, когда телефон находится в ландшафтном режиме

ответ

1

Вы можете сначала добавить NSNotification, чтобы узнать изменение ориентации на вашем устройстве в viewDidLoad.

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

Objective C Версия

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

Swift Версия

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