Изменить ориентацию программно с помощью кнопки - iOS - PullRequest
0 голосов
/ 17 мая 2018

У меня есть контроллер представления, и я хотел бы получить следующий опыт.Внутри контроллера вида у меня есть кнопка, которая заставляет вращать ориентацию вправо.

В Информации о развертывании - Ориентация устройства я включил «Пейзаж вправо» и «Портрет».

Я хочу упомянуть, что в моем устройстве я включил «Блокировку ориентации портрета», поэтому яЯ хочу, чтобы кнопка программно поворачивала ориентацию со следующим кодом.

let rotateButton: UIButton = {
    let btn = UIButton(type: .system)
    btn.setTitle("Rotate", for: .normal)
    btn.setTitleColor(.red, for: .normal)
    btn.addTarget(self, action: #selector(rotateTapped), for: .touchUpInside)
    return btn
}()

@objc func rotateTapped() {
    let value = UIInterfaceOrientation.landscapeRight.rawValue
    UIDevice.current.setValue(value, forKey: "orientation")
}

Таким образом, приведенный выше код работает правильно, и экран вращается.Хотя я хочу, чтобы пользователь поворачивался обратно в «Портрет», экран снова поворачивался в «Портрет» без нажатия какой-либо кнопки.Когда «Книжная ориентация заблокирована», экран не поворачивается обратно к портретному.

Я безуспешно пробовал следующие коды.

1)

    NotificationCenter.default.addObserver(self, selector: #selector(rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)


@objc func rotated() {
    if UIDevice.current.orientation.isLandscape {
        print("Landscape") //when the user taps the button this is being printed.
    } else {
        print("Portrait") //when the user rotates back to portrait this is NOT being printed.
    }
}

и 2)

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    if UIDevice.current.orientation == .landscapeRight {
        let value = UIInterfaceOrientation.portrait.rawValue
        UIDevice.current.setValue(value, forKey: "orientation")
    }
}

Есть ли какие-либо идеи о том, что может быть переключение обратно в портретное положение, когда пользователь снова поворачивает телефон?

Ответы [ 2 ]

0 голосов
/ 17 мая 2018
var currentOrientation: UIInterfaceOrientation = UIApplication.shared.statusBarOrientation
var value = .landscapeRight
UIDevice.current.setValue(value, forKey: "orientation")
UIViewController.attemptRotationToDeviceOrientation()
0 голосов
/ 17 мая 2018

У меня нет быстрого кода.Ниже приведен код objective c, он работал для меня.Вы можете преобразовать его в swift согласно вашему требованию.

Ojective C

UIInterfaceOrientation currentOrientation = [UIApplication sharedApplication].statusBarOrientation;
NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
[[UIDevice currentDevice] setValue:value forKey:@"orientation"];    
[UIViewController attemptRotationToDeviceOrientation];

Обновление

Swift 4.0

var value : Int = UIInterfaceOrientation.landscapeRight.rawValue
if UIApplication.shared.statusBarOrientation == .landscapeLeft || UIApplication.shared.statusBarOrientation == .landscapeRight{
   value = UIInterfaceOrientation.portrait.rawValue
}

UIDevice.current.setValue(value, forKey: "orientation")
UIViewController.attemptRotationToDeviceOrientation()

Выше код уже протестирован мной и работает нормально.Incase выше код не работает для вас, затем выполните его через некоторое время, используя performSelector.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...