UIWindow 窗口

前言

  • Objective-C

    1
    NS_CLASS_AVAILABLE_IOS(2_0) @interface UIWindow : UIView
  • Swift

    1
    @available(iOS 2.0, *) public class UIWindow : UIView

1、Window 的创建

  • Objective-C

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    // 声明窗口视图
    @property (strong, nonatomic) UIWindow *window;

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // 实例化窗口视图,window 的大小和当前手机屏幕一样大
    self.window = [[UIWindow alloc] initWithFrame: [UIScreen mainScreen].bounds];

    // 设置 window 的背景颜色
    self.window.backgroundColor = [UIColor whiteColor];

    // 将窗口显示到屏幕上
    [self.window makeKeyAndVisible];

    return YES;
    }
  • Swift

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    // 声明窗口视图
    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    // 实例化窗口视图,window 的大小和当前手机屏幕一样大
    self.window = UIWindow(frame: UIScreen.mainScreen().bounds)

    // 设置 window 的背景颜色
    self.window?.backgroundColor = UIColor.whiteColor()

    // 将窗口显示到屏幕上
    self.window?.makeKeyAndVisible()

    return true
    }

2、UIScreen 的使用

  • UIScreen 的属性

    • Objective-C

      1
      2
      3
      4
      5
      6
      7
      8
      // 带有状态栏的 Rect 
      CGRect bound = [UIScreen mainScreen].bounds;

      // 不带有状态栏的 Rect
      CGRect frame = [UIScreen mainScreen].applicationFrame;

      // 设备的自然分辨率
      float scale = [UIScreen mainScreen].scale;
  • scale 属性的进一步的说明:

    • 以前的 iPhone 设备屏幕分辨率都是 320x480,后来 apple 在 iPhone 4 中采用了名为 Retina 的显示技术,iPhone 4 采用了 960x640 像素分辨率的显示屏幕。由于屏幕大小没有变,还是 3.5 英寸,分辨率的提升将 iPhone 4 的显示分辨率提升至 iPhone 3GS 的四倍,每英寸的面积里有 326 个像素。

    • 简单的理解 scale 就是一个点有几个像素。scale 属性的值目前有 3 个:

      • scale = 1.0; iPhone 4 之前的设备
      • scale = 2.0; iPhone 4 ~ iPhone 7 (除 plus 外) 的设备
      • scale = 3.0; iPhone 6 plus 和 iPhone 7 plus 的设备

3、获取屏幕宽度与高度

  • 不同型号的 iOS 设备的屏幕尺寸:

    UIWindow1

  • Objective-C

    1
    2
    3
    4
    5
    // 当前屏幕的宽度
    CGFloat width = [UIScreen mainScreen].bounds.size.width;

    // 当前屏幕的高度
    CGFloat height = [UIScreen mainScreen].bounds.size.height;
  • Swift

    1
    2
    3
    4
    5
    // 当前屏幕的宽度
    let width: CGFloat = UIScreen.mainScreen().bounds.size.width

    // 当前屏幕的高度
    let height: CGFloat = UIScreen.mainScreen().bounds.size.height
文章目录
  1. 1. 前言
  2. 2. 1、Window 的创建
  3. 3. 2、UIScreen 的使用
  4. 4. 3、获取屏幕宽度与高度
隐藏目录