嗨,我想知道是否有办法以编程方式获取宽度。
我正在寻找足以容纳 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 属性将为您提供 UIWindow 坐标空间中视图的矩形,该坐标空间(默认情况下)不会考虑界面方向。
CGRect screen = [[UIScreen mainScreen] bounds];
CGFloat width = CGRectGetWidth(screen);
//Bonus height.
CGFloat height = CGRectGetHeight(screen);
这可以在 3 行代码中完成:
// 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
}
这些作为标准功能包含在:
https://github.com/goktugyil/EZSwiftExtensions
不定期副业成功案例分享