auto resize issue on subview appdelegate in iphone sdk - ios

in my app i will create some UIView in main window and UIView use auto resize but this is no support
if device mode is portrait then complatly work
but devicemode is landscape login view get x position in minus.
add view on window
_window = [UIApplication sharedApplication].keyWindow;
if (!_window) _window = [[UIApplication sharedApplication].windows objectAtIndex:0];
[[[_window subviews] objectAtIndex:0] addSubview:self.view_login];
image:
thanks in advance..

_window = [UIApplication sharedApplication].keyWindow;
if (!_window) _window = [[UIApplication sharedApplication].windows objectAtIndex:0];
UIInterfaceOrientation orientation = self.window.rootViewController.interfaceOrientation;
// Set appropriate view frame (it won't be autosized by addSubview:)
CGRect appFrame = [[UIScreen mainScreen] applicationFrame];
if (UIInterfaceOrientationIsLandscape(orientation))
{
// Need to flip the X-Y coordinates for landscape
self.view_login.frame = CGRectMake(appFrame.origin.y, appFrame.origin.x, appFrame.size.height, appFrame.size.width+40);
}
else
{
self.view_login.frame = appFrame;
}
[[[_window subviews] objectAtIndex:0] addSubview:self.view_login];

with this code you haven't set the autoresizing mask.
try this:
[self.view_login setAutoresizingMask:UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth];

Related

Objective - C, what does [UIScreen mainScreen].bounds.size.width actually give and what does initWithSize: actually require?

I am writing a GUI, with a main menu, a second screen and a back button to the main menu. From the initial main menu I use the following lines of code:
midScreenX = [UIScreen mainScreen].bounds.size.width/2;
midScreenY = [UIScreen mainScreen].bounds.size.height/2;
WarScene *battle = [[WarScene alloc] initWithSize: CGSizeMake(midScreenX*2, midScreenY*2)];
SKTransition *reveal = [SKTransition revealWithDirection:SKTransitionDirectionDown duration:1.0];
SKView * skView = (SKView *)self.view;
UIView *viewToRemove = [self.view viewWithTag:101];
[viewToRemove removeFromSuperview];
[skView presentScene:battle transition:reveal];
This works... I think. I open up a new scene, my second scene is the correct size and at least fills the screen. There is a node in that scene which is too big for the screen, and I am working on changing that, but I don't think that that would actually effect the UIScreen's bounds.
The problem arises when I return to the main menu with the following code:
midScreenX = [UIScreen mainScreen].bounds.size.width/2;
midScreenY = [UIScreen mainScreen].bounds.size.height/2;
GameScene *map = [[GameScene alloc] initWithSize: CGSizeMake(midScreenX*2 ,midScreenY*2)];
SKTransition *reveal = [SKTransition revealWithDirection:SKTransitionDirectionDown duration:1.0];
SKView * skView = (SKView *)self.view;
UIView *viewToRemove = [self.view viewWithTag:3];
[viewToRemove removeFromSuperview];
[skView presentScene:map transition:reveal];
As far as I can work out, the values being passed through should be exactly the same as the values initially sent for [UIScreen mainScreen].bounds.size and yet the scene which is initialised is far too big.
Is there anything that I could be doing which might affect [UIScreen mainScreen].bounds.size? Or have I misunderstood what init and .bounds actually do?
In terms of what I have already done to try and solve this problem myself, I have looked at examples of how scenes are normally initialised. I see that often values are used in place of .bounds for example :
initWithSize: CGSizeMake(1024,768)
However, wouldn't that mean that on different devices the scene wouldn't be shown properly/fully?
if you are using iOS 6 or iOS 7,
both [UIScreen mainScreen].bounds.size.width and [UIScreen mainScreen].bounds.size.height is same in all orientation..
but in iOS 8 it give one value in landscape and give another value in portrait mode
NSLog(#"width %f",[[UIScreen mainScreen] bounds].size.width); //portrait ios7 or 6 = 320 , landscape ios7 or 6 = 320
NSLog(#"height %f",[[UIScreen mainScreen] bounds].size.height); //portrait ios7 or 6 = 568 , landscape ios7 or 6 = 568
NSLog(#"width %f",[[UIScreen mainScreen] bounds].size.width); //portrait ios8 = 320 , landscape ios8 = 568
NSLog(#"height %f",[[UIScreen mainScreen] bounds].size.height); //portrait ios8 = 568 , landscape ios8 = 320
so we can check conditions like this,
CGFloat midScreenX,midScreenY;
if (UIDeviceOrientationIsLandscape((UIDeviceOrientation)[[UIApplication sharedApplication] statusBarOrientation]))
{
//landscape mode
midScreenX = ([[UIScreen mainScreen]bounds].size.width>[[UIScreen mainScreen]bounds].size.height?[[UIScreen mainScreen]bounds].size.width:[[UIScreen mainScreen]bounds].size.height)/2;
midScreenY = ([[UIScreen mainScreen]bounds].size.width<[[UIScreen mainScreen]bounds].size.height?[[UIScreen mainScreen]bounds].size.width:[[UIScreen mainScreen]bounds].size.height)/2;
}
else
{
//portrait mode
midScreenX = [[UIScreen mainScreen]bounds].size.width/2;
midScreenY = [[UIScreen mainScreen]bounds].size.height/2;
}
I hope you warScene and gameScene are subclass of SKScene. The method initWithSize returns, A newly initialized scene object. and parameter 'size' is The size of the scene in points.
For more information refer https://developer.apple.com/library/prerelease/ios/documentation/SpriteKit/Reference/SKScene_Ref/index.html#//apple_ref/occ/instm/SKScene/initWithSize:

Newly created UIWindow is sideways when app is opened on landscape

I have an iPad application in which I create a new UIWindow at the beginning of the app and show it while I do some resource synchronization. When the app is launched while the iPad is on portrait orientation, everything's fine. However, when on landscape orientation, the newly created UIWindow's size seems fine but it appears sideways and it's coordinates seem all weird. Here are the screenshots for both portrait and landscape orientations:
The landscape one is obtained by rotating to right once.
The piece of code where I create and show the UIWindow is as follows:
UIWindow *window=[UIApplication sharedApplication].keyWindow;
self.progressWindow = [[UIWindow alloc] initWithFrame:window.frame];
self.progressWindow.backgroundColor = [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.5f];
self.progressWindow.windowLevel = UIWindowLevelAlert;
/* some other code to create the subviews */
[self.progressWindow makeKeyAndVisible];
This problem only occurs on iOS 8.
As far as I understood, newly created UIWindow's do not rotate automatically when the orientation changes. I don't know whether this is new to iOS 8 or if it is a bug, but I was able to overcome the problem with the following piece of code:
UIWindow *window=[UIApplication sharedApplication].keyWindow;
self.progressWindow = [[UIWindow alloc] initWithFrame:window.frame];
self.progressWindow.backgroundColor = [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:0.5f];
self.progressWindow.windowLevel = UIWindowLevelAlert;
/* some other code to create the subviews */
[self handleOrientationChange];
[self.progressWindow makeKeyAndVisible];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(handleOrientationChange) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
Implementation for handleOrientationChange is as follows:
#define DegreesToRadians(degrees) (degrees * M_PI / 180)
- (void)handleOrientationChange
{
if (self.progressWindow)
{
// rotate the UIWindow manually
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
[self.progressWindow setTransform:[self transformForOrientation:orientation]];
// resize the UIWindow according to the new screen size
if ([[UIScreen mainScreen] respondsToSelector:#selector(nativeBounds)])
{
// iOS 8
CGRect screenRect = [UIScreen mainScreen].nativeBounds;
CGRect progressWindowFrame = self.progressWindow.frame;
progressWindowFrame.origin.x = 0;
progressWindowFrame.origin.y = 0;
progressWindowFrame.size.width = screenRect.size.width / [UIScreen mainScreen].nativeScale;
progressWindowFrame.size.height = screenRect.size.height / [UIScreen mainScreen].nativeScale;
self.progressWindow.frame = progressWindowFrame;
}
else
{
// iOs 7 or below
CGRect screenRect = [UIScreen mainScreen].bounds;
CGRect progressWindowFrame = self.progressWindow.frame;
progressWindowFrame.origin.x = 0;
progressWindowFrame.origin.y = 0;
progressWindowFrame.size.width = screenRect.size.width;
progressWindowFrame.size.height = screenRect.size.height;
self.progressWindow.frame = progressWindowFrame;
}
}
}
- (CGAffineTransform)transformForOrientation:(UIInterfaceOrientation)orientation {
switch (orientation) {
case UIInterfaceOrientationLandscapeLeft:
return CGAffineTransformMakeRotation(-DegreesToRadians(90));
case UIInterfaceOrientationLandscapeRight:
return CGAffineTransformMakeRotation(DegreesToRadians(90));
case UIInterfaceOrientationPortraitUpsideDown:
return CGAffineTransformMakeRotation(DegreesToRadians(180));
case UIInterfaceOrientationPortrait:
default:
return CGAffineTransformMakeRotation(DegreesToRadians(0));
}
}
I got the idea from the accepted answer of this question.
The shared application maintains a reference to the window through its
key- Window property:
let w = UIApplication.sharedApplication().keyWindow
That reference, however,
is slightly volatile, because the system can create temporary windows
and interpose them as the application’s key window.
try instead
[[UIApplication sharedApplication].delegate window]

iPad2 is stay portrait for a second before move to landscape

We have an app-which is ONLY landscape, that works great on ALL apple devices .
It also has the launch images .
We are lost with this bug.
We have set the app for landscape only in the device orientation menu.
All views are positioning in code only.
What happens on iPad2(iOS7) ONLY , is when you switch between views, you see for a second a portrait mode (which looks bad because graphics is for landscape only-so image is on half screen) and than it switch back to the landscape back after a second.
For some other views , the iPad2 ONLY stay forever on portrait for some reason -that means we see the graphics on half screen .its not positioned right .
the size of the screen that we get is just fine
float width=[UIScreen mainScreen].bounds.size.width;
float height=[UIScreen mainScreen].bounds.size.height;
768/1024
**** views that made with storyboard are ok- the others that positioning made with software are bad.
I use the following code (based on link given in above comment):
BOOL OSIsBelowIOS8 = [[[UIDevice currentDevice] systemVersion] floatValue] < 8.0;
if(OSIsBelowIOS8) {
if( [ [ UIScreen mainScreen ] respondsToSelector: #selector( nativeBounds ) ] )
{
self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] nativeBounds]];
}
else
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
}
} else {
self.window = [[UIWindow alloc] initWithFrame: [self screenBoundsOrientationDependent] ];
}
and this is my screenBoundsOrientationDependent
//Always return the iOS8 way - i.e. height is the real orientation dependent height
- (CGRect)screenBoundsOrientationDependent {
UIScreen *screen = [UIScreen mainScreen];
CGRect screenRect;
if (![screen respondsToSelector:#selector(fixedCoordinateSpace)] && UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation)) {
screenRect = CGRectMake(screen.bounds.origin.x, screen.bounds.origin.y, screen.bounds.size.height, screen.bounds.size.width);
} else {
screenRect = screen.bounds;
}
return screenRect;
}

UIScrollView issue on tapping UITextView or UITextField on keyboard presentation

I have a UIScrollView, which contains UITextFields and UITextViews. I have registered for the UIKeyboardDidChangeFrameNotification. When I tap on a text field or text view, the did change frame notification action is triggered and I adjust the contentOffset of the scroll view as shown below
- (void)keyboardDidChangeFrame:(NSNotification *)notification
{
CGRect keyboardEndFrame;
[[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardEndFrame];
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGRect intersection;
UIView *theFirstResponder = [[UIApplication sharedApplication].keyWindow findFirstResponder];
if ([theFirstResponder isKindOfClass:[UITextView class]]) {
if ([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationLandscapeLeft) {
keyboardEndFrame = CGRectMake(keyboardEndFrame.origin.y, 416, keyboardEndFrame.size.height, keyboardEndFrame.size.width);
}
else if ([UIApplication sharedApplication].statusBarOrientation == UIInterfaceOrientationLandscapeRight)
{
keyboardEndFrame = CGRectMake(keyboardEndFrame.origin.y, 0, keyboardEndFrame.size.height, keyboardEndFrame.size.width);
}
}
else
keyboardEndFrame = CGRectMake(keyboardEndFrame.origin.y, keyboardEndFrame.origin.x, keyboardEndFrame.size.height, keyboardEndFrame.size.width);
screenRect = CGRectMake(screenRect.origin.y, screenRect.origin.x, screenRect.size.height, screenRect.size.width);
if(CGRectEqualToRect(lastKBDRect, keyboardEndFrame)) {
return;
}
lastKBDRect = keyboardEndFrame;
if (CGRectIntersectsRect(keyboardEndFrame, screenRect)) {
// Keyboard is visible
//Convert Frame of the first responder, in context of the view that needs to be shifted
UIView *firstResponder = [[UIApplication sharedApplication].keyWindow findFirstResponder];
CGRect theRect = [firstResponder convertRect:firstResponder.frame toView:[UIApplication sharedApplication].keyWindow];
theRect = CGRectMake(theRect.origin.y, theRect.origin.x > 768 ? 750 : theRect.origin.x, theRect.size.height, theRect.size.width);
intersection = CGRectIntersection(keyboardEndFrame, theRect);
//If intersection is null, then no need to shift anything. Simply return.
if(CGRectIsNull(intersection)) {
return;
}
//Shift the view so that the first responder view is completely visible, keeping the constraint that the origin of the first responder view is also visible.
//Remember the current offset, so when we shift the view back, we shift it to the proper position.
if (!wasContentViewShifted) {
lastContentOffset = contentScrollView.contentOffset;
lastContentSize = contentScrollView.contentSize;
wasContentViewShifted = YES;
}
CGFloat offset = theRect.origin.y + theRect.size.height - keyboardEndFrame.origin.y;
if((theRect.origin.y - offset) < 40) {
offset += 42;
}
[UIView animateWithDuration:0.3f animations:^{
contentScrollView.contentOffset = CGPointMake(0, contentScrollView.contentOffset.y + offset);
contentScrollView.contentSize = CGSizeMake(0, lastContentSize.height + (600 - theRect.size.height));
}];
} else {
// Keyboard is hidden. Move the view back only if it was shifted.
if(wasContentViewShifted) {
wasContentViewShifted = NO;
[UIView animateWithDuration:0.3f animations:^{
contentScrollView.contentOffset = lastContentOffset;
contentScrollView.contentSize = lastContentSize;
}];
}
}
}
The application supports only landscape orientation.
The problems I'm facing here are
Tapping on textView presents the keyboard and textview is scrolled to the top if it is hidden by keyboard. Now, changing the orientation (landscape left to landscape Right) makes the textView scroll further to top and hence invisible.
The scrolling of TextView sometimes works for landscape left orientation but not for landscape right orientation and vice versa. This is because of the keyboardEndFrame values I'm using. Shouldn't I use the keyboardEndFrame origin values ? If not, what would be the alternative ?
Sometimes the it works for the textField but not for the textView.
Instead of having such complex solution you can try using this.
One simpler solution can also be found here.
Also it is not advisable to hard code the frames as you are doing. Refer to the apple documentation for more details.

How to get orientation-dependent height and width of the screen?

I'm trying to programmatically determine the current height and width of my application. I use this:
CGRect screenRect = [[UIScreen mainScreen] bounds];
But this yields a width of 320 and a height of 480, regardless of whether the device is in portrait or landscape orientation. How can I determine the current width and height (i.e. dependent upon the device orientation) of my main screen?
You can use something like UIInterfaceOrientationIsPortrait([UIApplication sharedApplication].statusBarOrientation) to determine the orientation and then use the dimensions accordingly.
HOWEVER, during an orientation change like in UIViewController's
- (void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
duration:(NSTimeInterval)duration
Use the orientation passed in toInterfaceOrientation since the UIApplication's statusBarOrientation will still point to the old orientation as it has not yet changed (since you're inside a will event handler).
Summary
There are several related posts to this, but each of them seem to indicate that you have to:
Look at [[UIScreen mainScreen] bounds] to get the dimensions,
Check what orientation you are in, and
Account for the status bar height (if shown)
Links
Iphone: Get current view dimensions or screen dimensions
IPhone/IPad: How to get screen width programmatically?
Objective C - how to get current screen resolution?
“Incorrect” frame / window size after re-orientation in iPhone or iPad
iPhone Dev SDK - get screen width
Working Code
I usually don't go this far, but you piqued my interest. The following code should do the trick. I wrote a Category on UIApplication. I added class methods for getting the currentSize or the size in a given orientation, which is what you would call in UIViewController's willRotateToInterfaceOrientation:duration:.
#interface UIApplication (AppDimensions)
+(CGSize) currentSize;
+(CGSize) sizeInOrientation:(UIInterfaceOrientation)orientation;
#end
#implementation UIApplication (AppDimensions)
+(CGSize) currentSize
{
return [UIApplication sizeInOrientation:[UIApplication sharedApplication].statusBarOrientation];
}
+(CGSize) sizeInOrientation:(UIInterfaceOrientation)orientation
{
CGSize size = [UIScreen mainScreen].bounds.size;
UIApplication *application = [UIApplication sharedApplication];
if (UIInterfaceOrientationIsLandscape(orientation))
{
size = CGSizeMake(size.height, size.width);
}
if (application.statusBarHidden == NO)
{
size.height -= MIN(application.statusBarFrame.size.width, application.statusBarFrame.size.height);
}
return size;
}
#end
To use the code simple call [UIApplication currentSize]. Also, I ran the above code, so I know it works and reports back the correct responses in all orientations. Note that I factor in the status bar. Interestingly I had to subtract the MIN of the status bar's height and width.
Other thoughts
You could go about getting the dimensions by looking at the UIWindow's rootViewController property. I've looked at this in the past and it similarly reports the same dimensions in both portrait and landscape except it reports having a rotate transform:
(gdb) po [[[[UIApplication sharedApplication] keyWindow]
rootViewController] view]
<UILayoutContainerView: 0xf7296f0; frame =
(0 0; 320 480); transform = [0, -1, 1, 0, 0, 0]; autoresize = W+H;
layer = <CALayer: 0xf729b80>>
(gdb) po [[[[UIApplication
sharedApplication] keyWindow] rootViewController] view]
<UILayoutContainerView: 0xf7296f0; frame = (0 0; 320 480); autoresize
= W+H; layer = <CALayer: 0xf729b80>>
Not sure how your app works, but if you aren't using a navigation controller of some kind, you could have a UIView under your main view with the max height / width of parent and grows / shrinks with parent. Then you could do: [[[[[[[UIApplication sharedApplication] keyWindow] rootViewController] view] subviews] objectAtIndex:0] frame]. That looks pretty intense on one line, but you get the idea.
However, it would still be better to do the above 3 steps under the summary. Start messing with UIWindows and you'll find out weird stuff, like showing a UIAlertView will change UIApplication's keywindow to point at a new UIWindow that the UIAlertView created. Who knew? I did after finding a bug relying on keyWindow and discovering that it changed like that!
This is my solution code !This method can add to NSObject class's Categroy , or you can define a Top custom UIViewController class , and let all of your other UIViewControllers to inherit it .
-(CGRect)currentScreenBoundsDependOnOrientation
{
CGRect screenBounds = [UIScreen mainScreen].bounds ;
CGFloat width = CGRectGetWidth(screenBounds) ;
CGFloat height = CGRectGetHeight(screenBounds) ;
UIInterfaceOrientation interfaceOrientation = [UIApplication sharedApplication].statusBarOrientation;
if(UIInterfaceOrientationIsPortrait(interfaceOrientation)){
screenBounds.size = CGSizeMake(width, height);
}else if(UIInterfaceOrientationIsLandscape(interfaceOrientation)){
screenBounds.size = CGSizeMake(height, width);
}
return screenBounds ;
}
Note, after IOS8 , as Apple Document of UIScreen's bounds property says :
Discussion
This rectangle is specified in the current coordinate space, which takes into account any interface rotations in effect for the device. Therefore, the value of this property may change when the device rotates between portrait and landscape orientations.
so for the consideration of compatibility , we should detect the IOS version and make the change as below:
#define IsIOS8 (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_7_1)
-(CGRect)currentScreenBoundsDependOnOrientation
{
CGRect screenBounds = [UIScreen mainScreen].bounds ;
if(IsIOS8){
return screenBounds ;
}
CGFloat width = CGRectGetWidth(screenBounds) ;
CGFloat height = CGRectGetHeight(screenBounds) ;
UIInterfaceOrientation interfaceOrientation = [UIApplication sharedApplication].statusBarOrientation;
if(UIInterfaceOrientationIsPortrait(interfaceOrientation)){
screenBounds.size = CGSizeMake(width, height);
}else if(UIInterfaceOrientationIsLandscape(interfaceOrientation)){
screenBounds.size = CGSizeMake(height, width);
}
return screenBounds ;
}
Here's a handy macro:
#define SCREEN_WIDTH (UIInterfaceOrientationIsPortrait([UIApplication sharedApplication].statusBarOrientation) ? [[UIScreen mainScreen] bounds].size.width : [[UIScreen mainScreen] bounds].size.height)
#define SCREEN_HEIGHT (UIInterfaceOrientationIsPortrait([UIApplication sharedApplication].statusBarOrientation) ? [[UIScreen mainScreen] bounds].size.height : [[UIScreen mainScreen] bounds].size.width)
In iOS 8+ you should use the viewWillTransitionToSize:withTransitionCoordinator method:
-(void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
// You can store size in an instance variable for later
currentSize = size;
// This is basically an animation block
[coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
// Get the new orientation if you want
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
// Adjust your views
[self.myView setFrame:CGRectMake(0, 0, size.width, size.height)];
} completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
// Anything else you need to do at the end
}];
}
This replaces the deprecated animation method that gave no information about size:
-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)orientation duration:(NSTimeInterval)duration
As of iOS 8 screen bounds are now returned correct for current orientation. This means an iPad in landscape orientation [UIScreen mainScreen].bounds would return 768 on iOS <=7 and 1024 on iOS 8.
The following returns the correct height and width on all versions released.
-(CGRect)currentScreenBoundsDependOnOrientation
{
NSString *reqSysVer = #"8.0";
NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
if ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending)
return [UIScreen mainScreen].bounds;
CGRect screenBounds = [UIScreen mainScreen].bounds ;
CGFloat width = CGRectGetWidth(screenBounds) ;
CGFloat height = CGRectGetHeight(screenBounds) ;
UIInterfaceOrientation interfaceOrientation = [UIApplication sharedApplication].statusBarOrientation;
if(UIInterfaceOrientationIsPortrait(interfaceOrientation)){
screenBounds.size = CGSizeMake(width, height);
NSLog(#"Portrait Height: %f", screenBounds.size.height);
}else if(UIInterfaceOrientationIsLandscape(interfaceOrientation)){
screenBounds.size = CGSizeMake(height, width);
NSLog(#"Landscape Height: %f", screenBounds.size.height);
}
return screenBounds ;
}
if you want the orientation dependent size and you have a view, you can just use:
view.bounds.size
I wrote category for UIScreen, that works on all iOS versions, so you can use it like this:
[[UIScreen mainScreen] currentScreenSize].
#implementation UIScreen (ScreenSize)
- (CGSize)currentScreenSize {
CGRect screenBounds = [[UIScreen mainScreen] bounds];
CGSize screenSize = screenBounds.size;
if ( NSFoundationVersionNumber <= NSFoundationVersionNumber_iOS_7_1 ) {
UIInterfaceOrientation interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
if ( UIInterfaceOrientationIsLandscape(interfaceOrientation) ) {
screenSize = CGSizeMake(screenSize.height, screenSize.width);
}
}
return screenSize;
}
#end
Here is a Swift way to get orientation dependent screen sizes:
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
}
These are included as a standard function in a project of mine:
https://github.com/goktugyil/EZSwiftExtensions
float msWidth = [[UIScreen mainScreen] bounds].size.width*(IS_RETINA?2.0f:1.0f);
float msHeight = [[UIScreen mainScreen] bounds].size.height*(IS_RETINA?2.0f:1.0f);
if ( UIInterfaceOrientationIsPortrait(self.interfaceOrientation) ) {
os->setWidth(MIN(msWidth, msHeight));
os->setHeight(MAX(msWidth, msHeight));
} else {
os->setWidth(MAX(msWidth, msHeight));
os->setHeight(MIN(msWidth, msHeight));
}
NSLog(#"screen_w %f", os->getWidth());
NSLog(#"screen_h %f", os->getHeight());
However, on iOS 8.0.2:
+ (NSUInteger)currentWindowWidth
{
NSInteger width = 0;
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
CGSize size = [UIScreen mainScreen].bounds.size;
// if (UIInterfaceOrientationIsLandscape(orientation)) {
// width = size.height;
// } else {
width = size.width;
// }
return width;
}
use -> setNeedsDisplay() for the view you want to resize.
Some improvements on the answers offered here, in Swift:
let interfaceOrientation = UIApplication.shared.statusBarOrientation // (< iOS 13)
let screenSize = UIScreen.main.bounds.size
let screenWidth = interfaceOrientation.isPortrait ? screenSize.width : screenSize.height
let screenHeight = interfaceOrientation.isPortrait ? screenSize.height : screenSize.width

Resources