iOS에서 화면 너비와 높이를 얻는 방법은 무엇입니까?
iOS에서 화면의 크기를 어떻게 알 수 있습니까?
현재는 다음을 사용합니다.
lCurrentWidth = self.view.frame.size.width;
lCurrentHeight = self.view.frame.size.height;
에서 viewWillAppear:
와willAnimateRotationToInterfaceOrientation:duration:
처음으로 전체 화면 크기를 얻습니다. 두 번째로 화면에서 탐색 모음을 뺀 것입니다.
iOS에서 화면의 크기를 어떻게 알 수 있습니까?
게시 한 코드의 문제점은 화면의 크기와 일치하도록 뷰 크기를 계산하고 있다는 것을 항상 알 수 있습니다. 화면 크기가 필요한 경우 다음과 같이 화면 자체를 나타내는 객체를 확인해야합니다.
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
분할보기 업데이트 : 의견에서 Dmitry는 다음과 같이 물었습니다.
분할보기에서 화면 크기를 어떻게 얻을 수 있습니까?
위에 제공된 코드는 분할 화면 모드에서도 화면 크기를보고합니다. 분할 화면 모드를 사용하면 앱의 창이 변경됩니다. 위의 코드가 예상 한 정보를 제공하지 않으면 OP와 마찬가지로 잘못된 객체를보고 있습니다. 이 경우 화면 대신 창을 다음과 같이보아야합니다.
CGRect windowRect = self.view.window.frame;
CGFloat windowWidth = windowRect.size.width;
CGFloat windowHeight = windowRect.size.height;
스위프트 4.2
let screenRect = UIScreen.main.bounds
let screenWidth = screenRect.size.width
let screenHeight = screenRect.size.height
// split screen
let windowRect = self.view.window?.frame
let windowWidth = windowRect?.size.width
let windowHeight = windowRect?.size.height
주의 [UIScreen mainScreen]에는 상태 표시 줄도 포함되어 있습니다. 응용 프로그램 (상태 표시 줄 제외)의 프레임을 검색하려면 사용해야합니다.
+ (CGFloat) window_height {
return [UIScreen mainScreen].applicationFrame.size.height;
}
+ (CGFloat) window_width {
return [UIScreen mainScreen].applicationFrame.size.width;
}
위의 Objective-C 답변 중 일부를 Swift 코드로 번역했습니다. 각 번역은 원래 답변에 대한 참조로 진행됩니다.
주요 답변
let screen = UIScreen.main.bounds
let screenWidth = screen.size.width
let screenHeight = screen.size.height
간단한 함수 답변
func windowHeight() -> CGFloat {
return UIScreen.mainScreen().applicationFrame.size.height
}
func windowWidth() -> CGFloat {
return UIScreen.mainScreen().applicationFrame.size.width
}
장치 방향 답변
var screenHeight : CGFloat
let statusBarOrientation = UIApplication.sharedApplication().statusBarOrientation
// it is important to do this after presentModalViewController:animated:
if (statusBarOrientation != UIInterfaceOrientation.Portrait
&& statusBarOrientation != UIInterfaceOrientation.PortraitUpsideDown){
screenHeight = UIScreen.mainScreen().applicationFrame.size.width
} else {
screenHeight = UIScreen.mainScreen().applicationFrame.size.height
}
로그 답변
let screenWidth = UIScreen.mainScreen().bounds.size.width
let screenHeight = UIScreen.mainScreen().bounds.size.height
println("width: \(screenWidth)")
println("height: \(screenHeight)")
나는 이러한 편의 방법을 전에 사용했다 :
- (CGRect)getScreenFrameForCurrentOrientation {
return [self getScreenFrameForOrientation:[UIApplication sharedApplication].statusBarOrientation];
}
- (CGRect)getScreenFrameForOrientation:(UIInterfaceOrientation)orientation {
CGRect fullScreenRect = [[UIScreen mainScreen] bounds];
// implicitly in Portrait orientation.
if (UIInterfaceOrientationIsLandscape(orientation)) {
CGRect temp = CGRectZero;
temp.size.width = fullScreenRect.size.height;
temp.size.height = fullScreenRect.size.width;
fullScreenRect = temp;
}
if (![[UIApplication sharedApplication] statusBarHidden]) {
CGFloat statusBarHeight = 20; // Needs a better solution, FYI statusBarFrame reports wrong in some cases..
fullScreenRect.size.height -= statusBarHeight;
}
return fullScreenRect;
}
나는 이것이 오래된 게시물이라는 것을 알고 있지만 때로는 이러한 상수를 #define하는 것이 유용하므로 걱정할 필요가 없습니다.
#define DEVICE_SIZE [[[[UIApplication sharedApplication] keyWindow] rootViewController].view convertRect:[[UIScreen mainScreen] bounds] fromView:nil].size
위의 상수는 장치 방향에 관계없이 올바른 크기를 반환해야합니다. 그런 다음 치수를 얻는 것은 다음과 같이 간단합니다.
lCurrentWidth = DEVICE_SIZE.width;
lCurrentHeight = DEVICE_SIZE.height;
기기 크기 를 파악 하고 방향을 고려하는 것은 매우 쉽습니다 .
// 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];
우리는 장치의 방향도 고려해야합니다.
CGFloat screenHeight;
// it is important to do this after presentModalViewController:animated:
if ([[UIApplication sharedApplication] statusBarOrientation] == UIDeviceOrientationPortrait || [[UIApplication sharedApplication] statusBarOrientation] == UIDeviceOrientationPortraitUpsideDown){
screenHeight = [UIScreen mainScreen].applicationFrame.size.height;
}
else{
screenHeight = [UIScreen mainScreen].applicationFrame.size.width;
}
NSLog(@"%.0f", [[UIScreen mainScreen] bounds].size.width);
NSLog(@"%.0f", [[UIScreen mainScreen] bounds].size.height);
여기에 스위프트 3 업데이트되었습니다
iOS 9에서 사용되지 않는 applicationFrame
신속한 세에서 그들은 제거했다 () 그리고 그들은, 당신이 여기에서 참조 할 수 있습니다 몇 가지 이름 지정 규칙을 변경 한 링크
func windowHeight() -> CGFloat {
return UIScreen.main.bounds.size.height
}
func windowWidth() -> CGFloat {
return UIScreen.main.bounds.size.width
}
이를 사용 Structs
하여 Swift 3.0의 현재 장치에 대한 유용한 정보를 알 수 있습니다
struct ScreenSize { // Answer to OP's question
static let SCREEN_WIDTH = UIScreen.main.bounds.size.width
static let SCREEN_HEIGHT = UIScreen.main.bounds.size.height
static let SCREEN_MAX_LENGTH = max(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
static let SCREEN_MIN_LENGTH = min(ScreenSize.SCREEN_WIDTH, ScreenSize.SCREEN_HEIGHT)
}
struct DeviceType { //Use this to check what is the device kind you're working with
static let IS_IPHONE_4_OR_LESS = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH < 568.0
static let IS_IPHONE_SE = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 568.0
static let IS_IPHONE_7 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 667.0
static let IS_IPHONE_7PLUS = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 736.0
static let IS_IPHONE_X = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.SCREEN_MAX_LENGTH == 812.0
static let IS_IPAD = UIDevice.current.userInterfaceIdiom == .pad && ScreenSize.SCREEN_MAX_LENGTH == 1024.0
}
struct iOSVersion { //Get current device's iOS version
static let SYS_VERSION_FLOAT = (UIDevice.current.systemVersion as NSString).floatValue
static let iOS7 = (iOSVersion.SYS_VERSION_FLOAT >= 7.0 && iOSVersion.SYS_VERSION_FLOAT < 8.0)
static let iOS8 = (iOSVersion.SYS_VERSION_FLOAT >= 8.0 && iOSVersion.SYS_VERSION_FLOAT < 9.0)
static let iOS9 = (iOSVersion.SYS_VERSION_FLOAT >= 9.0 && iOSVersion.SYS_VERSION_FLOAT < 10.0)
static let iOS10 = (iOSVersion.SYS_VERSION_FLOAT >= 10.0 && iOSVersion.SYS_VERSION_FLOAT < 11.0)
static let iOS11 = (iOSVersion.SYS_VERSION_FLOAT >= 11.0 && iOSVersion.SYS_VERSION_FLOAT < 12.0)
static let iOS12 = (iOSVersion.SYS_VERSION_FLOAT >= 12.0 && iOSVersion.SYS_VERSION_FLOAT < 13.0)
}
장치 방향에 관계없이 화면 너비 / 높이를 원하는 경우 (가로 방향에서 시작되는 세로 방향보기 컨트롤러의 크기 조정에 적합) :
CGFloat screenWidthInPoints = [UIScreen mainScreen].nativeBounds.size.width/[UIScreen mainScreen].nativeScale;
CGFloat screenHeightInPoints = [UIScreen mainScreen].nativeBounds.size.height/[UIScreen mainScreen].nativeScale;
[UIScreen mainScreen] .nativeBounds <-문서에서-> 실제 화면의 경계 사각형 (픽셀 단위). 이 사각형은 세로 방향의 장치를 기준으로합니다. 장치가 회전해도이 값은 변경되지 않습니다.
화면 크기를 얻는 신속한 방법은 다음과 같습니다.
print(screenWidth)
print(screenHeight)
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
CGFloat width = [[UIScreen mainScreen] bounds].size.width; CGFloat height = [[UIScreen mainScreen]bounds ].size.height;
현대적인 답변 :
응용 프로그램이 iPad에서 분할보기를 지원하면이 문제가 조금 복잡해집니다. 화면 크기가 아닌 창 크기가 필요하며 여기에는 2 개의 앱이 포함될 수 있습니다. 실행하는 동안 창의 크기도 다를 수 있습니다.
앱의 기본 창의 크기를 사용하십시오.
UIApplication.shared.delegate?.window??.bounds.size ?? .zero
참고 : 위의 방법은 시작할 때 창이 키 윈도우가되기 전에 잘못된 값을 얻을 수 있습니다. 너비 만 필요한 경우 아래 방법을 사용하는 것이 좋습니다 .
UIApplication.shared.statusBarFrame.width
이전 솔루션을 사용 UIScreen.main.bounds
하면 장치의 경계가 반환됩니다. 앱이 분할보기 모드에서 실행중인 경우 크기가 잘못됩니다.
self.view.window
앱에 둘 이상의 창이 포함되어 있고 창의 크기가 작을 때 가장 인기있는 답변의 크기가 잘못 될 수 있습니다.
스위프트 3.0
너비
UIScreen.main.bounds.size.width
높이
UIScreen.main.bounds.size.height
이 매크로를 pch 파일에 배치하고 "SCREEN_WIDTH"를 사용하여 프로젝트의 어느 곳에서나 사용할 수 있습니다
#define SCREEN_WIDTH ((([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortrait) || ([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortraitUpsideDown)) ? [[UIScreen mainScreen] bounds].size.width : [[UIScreen mainScreen] bounds].size.height)
"SCREEN_HEIGHT"
#define SCREEN_HEIGHT ((([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortrait) || ([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationPortraitUpsideDown)) ? [[UIScreen mainScreen] bounds].size.height : [[UIScreen mainScreen] bounds].size.width)
사용 예 :
CGSize calCulateSizze ;
calCulateSizze.width = SCREEN_WIDTH/2-8;
calCulateSizze.height = SCREEN_WIDTH/2-8;
참고 URL : https://stackoverflow.com/questions/5677716/how-to-get-the-screen-width-and-height-in-ios
'Programming' 카테고리의 다른 글
사용자 입력 및 명령 행 인수 (0) | 2020.02.12 |
---|---|
파이썬 : 목록에서 찾기 (0) | 2020.02.12 |
Swift에서 문자열에 다른 문자열이 포함되어 있는지 어떻게 확인합니까? (0) | 2020.02.12 |
Java에서 바이트 크기를 사람이 읽을 수있는 형식으로 변환하는 방법은 무엇입니까? (0) | 2020.02.12 |
UIDevice uniqueIdentifier 더 이상 사용되지 않음-지금 무엇을해야합니까? (0) | 2020.02.12 |