[ SWIFT ] - FUNC - 判斷裝置與取得目前裝置 方向 & SIZE

判斷裝置:traitCollection

if( self.traitCollection.userInterfaceIdiom == UIUserInterfaceIdiom.Pad)
        {NSLog("裝置為iPad")}
if( self.traitCollection.userInterfaceIdiom == UIUserInterfaceIdiom.Phone)

        {NSLog("裝置為iPhone")}

判斷裝置目前螢幕方向(當裝置方向改變時呼叫):willTransitionToTraitCollection

override func willTransitionToTraitCollection(newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
        
        super.willTransitionToTraitCollection(newCollection, withTransitionCoordinator: coordinator)
        if( newCollection.horizontalSizeClass == UIUserInterfaceSizeClass.Compact)
        {
          NSLog("Compact Width")
        }
        
        if( newCollection.horizontalSizeClass == UIUserInterfaceSizeClass.Regular)
        {
            NSLog("Regular Width")
        }
        
        if( newCollection.verticalSizeClass == UIUserInterfaceSizeClass.Compact)
        {
            NSLog("Compact Height")
        }
        
        if( newCollection.verticalSizeClass == UIUserInterfaceSizeClass.Regular)
        {
            NSLog("Regular Height")

        }

判斷裝置最後方向與螢幕解析度:
viewWillTransitionToSize:當view得尺寸改變時呼叫。


 override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
        
        var orientation:UIDeviceOrientation = UIDevice.currentDevice().orientation
        if (orientation == UIDeviceOrientation.LandscapeLeft)
        {
        NSLog("橫向,頂端再左側")
        }
        
        if (orientation == UIDeviceOrientation.LandscapeRight)
        {
            NSLog("橫向,頂端再右側")
        }
        
        if (orientation == UIDeviceOrientation.Portrait)
        {
            NSLog("直向")
        }
        
        if (orientation == UIDeviceOrientation.PortraitUpsideDown)
        {
            NSLog("直向但上下顛倒")
        }
        
        if (orientation == UIDeviceOrientation.Unknown)
        {
            NSLog("方向未知")
        }
        
        var bounds: CGRect = UIScreen.mainScreen().bounds
        var screenWidth : CGFloat = bounds.width;
        var screenHeight : CGFloat = bounds.height;
        NSLog("解析度為:%fx%f",Float(screenWidth),Float(screenHeight))


    }

留言

熱門文章