OC开发——iOS获取屏幕宽高、设备型号、系统版本信息

1、获取屏幕的宽高

屏幕的宽高是一个常常需要用到的信息,尤其是当你用代码写UI时。比如当你写一个UILabel,设置其frame时,你想要它居中,而你想为其设置的宽度为200,那怎么设置它的x值呢?就是(屏幕的宽度 - 200)/ 2了对吧,这样就可以保证不管在什么设备上它永远是居中的。获取屏幕宽、高的方法如下:

// 设备宽度
 [UIScreen mainScreen].bounds.size.width
 
// 设备高度
[UIScreen mainScreen].bounds.size.height


一般来说我们在pch文件里将其设置为宏,这样在每个地方就都可以调用了,就不用每次都用这么长一串代码:

//设备的宽高
#define SCREENWIDTH       [UIScreen mainScreen].bounds.size.width
#define SCREENHEIGHT      [UIScreen mainScreen].bounds.size.height
 


这样在需要用的地方直接使用宏SCREENWIDTH和SCREENHEIGHT就可以了。

2、获取设备的型号

获取设备型号有几种方法,这里我使用的是比较笨的方法,获取设备的分辨率来判断设备的型号。我们先看下面这张表:

设备

iPhone

Width

Height

对角线

Diagonal

逻辑分辨率(point)

Scale Factor

设备分辨率(pixel)

PPI

3GS

2.4 inches (62.1 mm)

4.5 inches (115.5 mm)

3.5-inch

320x480

@1x

320x480

163

4(s)

2.31 inches (58.6 mm)

4.5 inches (115.2 mm)

3.5-inch

320x480

@2x

640x960

326

5c

2.33 inches (59.2 mm)

4.90 inches (124.4 mm)

4-inch

320x568

@2x

640x1136

326

5(s)

2.31 inches (58.6 mm)

4.87 inches (123.8 mm)

4-inch

320x568

@2x

640x1136

326

6(s)

2.64 inches (67.0 mm)

5.44 inches (138.1 mm)

4.7-inch

375x667

@2x

750x1334

326

6(s)+

3.06 inches (77.8 mm)

6.22 inches (158.1 mm)

5.5-inch

414x736

@3x

(1242x2208->)

1080x1920

401 

关注设备分辨率那一列,我们可以看到几款屏幕的设备的分辨率是不同的,因此也就可以以此为依据判断设备型号,我这里判断了几种当前最常见的型号,同样使用了宏:

// 根据屏幕分辨率判断设备,是则返回YES,不是返回NO


#define isiPhone5or5sor5c ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO)
#define isiPhone6or6s ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(750, 1334), [[UIScreen mainScreen] currentMode].size) : NO)
#define isiPhone6plusor6splus ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2208), [[UIScreen mainScreen] currentMode].size) : NO)


那么我只需要判断这几个值哪一个是YES,就可以知道当前是哪个型号了,如:

    if (isiPhone5or5sor5c) {
        NSLog(@"这是 iPhone5 或 5s 或 5c") ;
    } else if (isiPhone6or6s) {
        NSLog(@"这是 iPhone6 或 6s");
    } else if (isiPhone6plusor6splus) {
        NSLog(@"这是 iPhone6plus 或6splus");
    }


这样就可以啦。

其实相应的iPad、iTouch等也都可以这么判断,只要找到对应的分辨率来判断就好。

3、获取系统版本

获取系统版本同样适用宏来方便全局调用:

// 设备的系统版本
#define SystemVersion ([[UIDevice currentDevice] systemVersion])

这样你就可以获取版本号了,可以打印出来:

NSLog(@"当前运行系统为:iOS%@", SystemVersion);


在使用的时候,可以转化为float型的数来进行判断,如:

    if ([SystemVersion floatValue] >= 7.0)
    {
        ……
    }
 

猜你喜欢

转载自blog.csdn.net/lvshitianxia/article/details/81781964