繁体   English   中英

设备旋转通知无法按预期方式运行iOS Swift

[英]Device Rotation Notification is not working as expected iOS Swift

    func shouldirotate(){

    var whichwaywhere: String {

        if UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeLeft {
            return "left"
        }
        if UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeRight {
            return "right"
        }
        if UIDevice.currentDevice().orientation == UIDeviceOrientation.PortraitUpsideDown {
            return "down"
        }
        return "I don't Care"
    }
    println(whichwaywhere)
}

当我创建一个不断自我检查的功能时(将应附加到NSTimer上),我可以检查方向。 当UIDeviceOrientationDidChangeNotification激活时,如何告诉函数运行?

为了使UIDeviceOrientationDidChangeNotification运行,我有一个变量:

var rotatenote: Bool = UIDevice.currentDevice().generatesDeviceOrientationNotifications

在ViewDidLoad重写中,我有:

override func viewDidLoad() {
    UIDevice.currentDevice().beginGeneratingDeviceOrientationNotifications()
    rotatenote = true
}

这是使用和声明此属性的正确方法吗? 我怎样才能让该函数在DeviceOrientationNotification中运行?

PS:我在ViewDidLoad中具有rotatenote = true,因为如果我像往常一样尝试将其附加到变量声明,它会说“无法分配给该表达式的结果”。 见下文

var rotatenote: Bool = UIDevice.currentDevice().generatesDeviceOrientationNotifications = true

有几种方法可以做到这一点。 不确定您担心的操作系统是什么,但是在iOS 8中,您有两个简单的选择。 您可以注册一名观察员

UIDeviceOrientationDidChangeNotification

或者您可以覆盖

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

应该需要

UIDevice.currentDevice().beginGeneratingDeviceOrientationNotifications()

因此,可以在viewDidLoad中添加:

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

在哪里有函数functionThatYouWantTriggeredOnRotation进行计算...

或者,您可以仅提供viewWillTransition的替代,而不必为UIDeviceOrientationDidChangeNotification添加观察者。

override func viewWillTransitionToSize(size: CGSize,
      withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator)
{
    if UIDevice.currentDevice().orientation.isLandscape {
            //do your thing
        }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM