[iphone] iPhone / IPad : 프로그래밍 방식으로 화면 너비를 얻는 방법은 무엇입니까?

안녕하세요 프로그래밍 방식으로 너비를 얻는 방법이 있는지 궁금합니다.

나는 iphone 3gs, iphone 4, ipad를 수용하기에 충분히 일반적인 것을 찾고 있습니다. 또한 기기가 세로인지 가로인지에 따라 너비가 변경되어야합니다 (ipad의 경우).

아무도 이것을하는 방법을 알고 있습니까 ?? 오랜만에 찾고 있었는데 … 고마워!



답변

UIScreen을 살펴보십시오 .

예.

CGFloat width = [UIScreen mainScreen].bounds.size.width;

상태 표시 줄을 포함하지 않으려면 applicationFrame 속성을 살펴보십시오 (너비에 영향을주지 않음).

업데이트 : UIScreen (-bounds 또는 -applicationFrame)이 현재 인터페이스 방향을 고려하지 않는 것으로 나타났습니다. 보다 정확한 접근 방식은 UIView에 경계를 요청하는 것입니다.이 UIView가 View 컨트롤러에 의해 자동 회전되었다고 가정합니다.

- (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];


답변

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


답변

사용하다:

NSLog(@"%f",[[UIScreen mainScreen] bounds].size.width) ;


답변

다음은 화면 크기를 가져 오는 신속한 방법이며 현재 인터페이스 방향도 고려합니다.

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