嗨,我想知道是否有一种方法可以以编程方式获取宽度。
我正在寻找一个足够通用的解决方案,可以适应iPhone 3GS、iPhone 4和iPad。此外,对于iPad设备,宽度应基于横向或纵向模式而改变。
有人知道如何实现吗?我已经寻找了一段时间...谢谢!
嗨,我想知道是否有一种方法可以以编程方式获取宽度。
我正在寻找一个足够通用的解决方案,可以适应iPhone 3GS、iPhone 4和iPad。此外,对于iPad设备,宽度应基于横向或纵向模式而改变。
有人知道如何实现吗?我已经寻找了一段时间...谢谢!
请查看UIScreen。
例如:
CGFloat width = [UIScreen mainScreen].bounds.size.width;
如果您不想包含状态栏,可以查看applicationFrame属性(不会影响宽度)。
更新:事实证明UIScreen(-bounds或-applicationFrame)不考虑当前界面方向。更正确的方法是询问您的UIView其边界-假设此UIView已由其视图控制器自动旋转。
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
CGFloat width = CGRectGetWidth(self.view.bounds);
}
如果视图不是由视图控制器自动旋转的,则需要检查界面方向以确定视图边界的哪一部分表示“宽度”和“高度”。请注意,frame属性将为您提供窗口坐标空间中视图的矩形,该坐标空间(默认情况下)不会考虑接口方向。
CGRect screen = [[UIScreen mainScreen] bounds];
CGFloat width = CGRectGetWidth(screen);
//Bonus height.
CGFloat height = CGRectGetHeight(screen);
这可以用三行代码完成:
// grab the window frame and adjust it for orientation
UIView *rootView = [[[UIApplication sharedApplication] keyWindow]
rootViewController].view;
CGRect originalFrame = [[UIScreen mainScreen] bounds];
CGRect adjustedFrame = [rootView convertRect:originalFrame fromView:nil];
NSLog(@"%f",[[UIScreen mainScreen] bounds].size.width) ;
iOS 9.0及以上版本目前无法可靠地获取方向。以下是我为一款仅支持竖屏模式设计的应用所使用的代码,因此,即使在横屏模式下打开应用程序,它仍将保持准确:
screenHeight = [[UIScreen mainScreen] bounds].size.height;
screenWidth = [[UIScreen mainScreen] bounds].size.width;
if (screenWidth > screenHeight) {
float tempHeight = screenWidth;
screenWidth = screenHeight;
screenHeight = tempHeight;
}
使用这段代码会有帮助
[[UIScreen mainScreen] bounds].size.height
[[UIScreen mainScreen] bounds].size.width
这里是一个获取屏幕尺寸的 Swift 方法,同时考虑了当前的界面方向:
var screenWidth: CGFloat {
if UIInterfaceOrientationIsPortrait(screenOrientation) {
return UIScreen.mainScreen().bounds.size.width
} else {
return UIScreen.mainScreen().bounds.size.height
}
}
var screenHeight: CGFloat {
if UIInterfaceOrientationIsPortrait(screenOrientation) {
return UIScreen.mainScreen().bounds.size.height
} else {
return UIScreen.mainScreen().bounds.size.width
}
}
var screenOrientation: UIInterfaceOrientation {
return UIApplication.sharedApplication().statusBarOrientation
}
这些被包含在标准函数中: