I am working on a photography app that allow photos to be taken in portrait or landscape. Due to the requirements of the project, I cannot let the device orientation autorotate, but rotation does need to be supported.
When using the following orientation methods:
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if self.orientation == .Landscape {
return UIInterfaceOrientationMask.LandscapeRight
} else {
return UIInterfaceOrientationMask.Portrait
}
}
override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {
if self.orientation == .Landscape {
return UIInterfaceOrientation.LandscapeRight
} else {
return UIInterfaceOrientation.Portrait
}
}
I am able to set rotation correctly at launch. By changing the orientation value and calling UIViewController.attemptRotationToDeviceOrientation() I am able to support rotation to the new desired interface. However, this rotation only occurs when the user actually moves their device. I need it to happen automatically.
I am able to call: UIDevice.currentDevice().setValue(targetOrientation.rawValue, forKey: "orientation") to force the change, but that causes other side effects because UIDevice.currentDevice().orientation only returns the setValue from that point on. (and it's extremely dirty)
Is there something I'm missing? I've looked into closing and launching a new view controller, but that has other issues such as a constant UI glitch when dismissing and immediately presenting a new view controller.
EDIT:
The following methods did not work for me:
Trick preferredInterfaceOrientationForPresentation to fire on viewController change
Forcing UIInterfaceOrientation changes on iPhone
EDIT 2:
Thoughts on potential solutions:
set orientation directly (with setValue) and deal with all the side effects this presents on iOS 9 (not acceptable)
I can use the current solution and indicate that the user needs to rotate the device. Once the device has been physically rotated, the UI rotates and then locks in place correctly. (poor UI)
I can find a solution that forces the refresh of orientation and rotates without physical action. (what I'm asking about, and looking for)
Do it all by hand. I can lock the interface in portrait or landscape, and manually rotate and resize the container view. This is 'dirty' because it forgoes all of the size class autolayout features and causes much heavier code. I am trying to avoid this.
I was able to find a solution with the assistance of this answer: Programmatic interface orientation change not working for iOS
My base orientation logic is as follows:
// Local variable to tracking allowed orientation. I have specific landscape and
// portrait targets and did not want to remember which I was supporting
enum MyOrientations {
case Landscape
case Portrait
}
var orientation: MyOrientations = .Landscape
// MARK: - Orientation Methods
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if self.orientation == .Landscape {
return UIInterfaceOrientationMask.LandscapeRight
} else {
return UIInterfaceOrientationMask.Portrait
}
}
override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {
if self.orientation == .Landscape {
return UIInterfaceOrientation.LandscapeRight
} else {
return UIInterfaceOrientation.Portrait
}
}
// Called on region and delegate setters
func refreshOrientation() {
if let newOrientation = self.delegate?.getOrientation() {
self.orientation = newOrientation
}
}
Then when I want to refresh the orientation, I do the following:
// Correct Orientation
let oldOrientation = self.orientation
self.refreshOrientation()
if self.orientation != oldOrientation {
dispatch_async(dispatch_get_main_queue(), {
self.orientationRefreshing = true
let vc = UIViewController()
UIViewController.attemptRotationToDeviceOrientation()
self.presentViewController(vc, animated: false, completion: nil)
UIView.animateWithDuration(0.3, animations: {
vc.dismissViewControllerAnimated(false, completion: nil)
})
})
}
This solution has the side effect of causing view[Will/Did]Appear and view[Will/Did]Disappear to fire all at once. I'm using the local orientationRefreshing variable to manage what aspects of those methods are called again.
I've encountered this exact problem in the past, myself. I was able to solve it using a simple work around (and GPUImage). My code is in Objective-C but i'm sure you'll have no problem translating it to Swift.
I began by setting the project's supported rotations to all that I hoped to support and then overriding the same UIViewController methods:
-(BOOL)shouldAutorotate {
return TRUE;
}
-(NSUInteger)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskPortrait;
}
Which allows the device to rotate but will persist in Portrait mode. Then began observing for Device rotations:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(adjustForRotation:)
name:UIDeviceOrientationDidChangeNotification
object:nil];
Then updated the UI if the device was in Portrait mode or landscape:
-(void)adjustForRotation:(NSNotification*)notification
{
UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
switch (orientation) {
case UIDeviceOrientationLandscapeLeft:
{
// UPDATE UI
}
break;
case UIDeviceOrientationLandscapeRight:
{
// UPDATE UI
}
break;
default: // All other orientations - Portrait, Upside Down, Unknown
{
// UPDATE UI
}
break;
}
}
And finally, GPUImage rendered the image based on the device's orientation.
[_gpuImageStillCamera capturePhotoAsImageProcessedUpToFilter:last_f
withCompletionHandler:^(UIImage *processedImage, NSError *error) {
// Process the processedImage
}];
So I looked at the private headers of UIDevice, and it appears that there are two setters, and two property definitions, for orientation, which is currently baffling me. This is what I saw...
#property (nonatomic) int orientation;
#property (nonatomic, readonly) int orientation;
- (void)setOrientation:(int)arg1;
- (void)setOrientation:(int)arg1 animated:(BOOL)arg2;
So when I saw that you used setValue:forKey:, I wanted to see there was a synthesized setter and getter, and am honestly not 100% sure as to which one is being set, and which one is being acknowledged by the device... I attempted in a demo app to use setValue:forKey: to no avail, but used this trick from one of my past applications, and it did the trick right away :) I hope this helps
UIDevice.currentDevice().performSelector(Selector("setOrientation:"), withObject: UIInterfaceOrientation.Portrait.rawValue)
I need to support all interface orientation masks in my App.
Some view controller shouldn't autorotate(it supports Portrait orientation only), but the App still need to support all orientations.
Expected result
I tried to set shouldAutorotate = true; supportedInterfaceOrientations = All in UINavigationController and shouldAutorotate = false; supportedInterfaceOrientations = Portrait in root view controller. But it's not working.
You can use this in viewControllers that support only Portrait mode
override func shouldAutorotate() -> Bool {
if (UIDevice.currentDevice().orientation == UIDeviceOrientation.Portrait ||
UIDevice.currentDevice().orientation == UIDeviceOrientation.PortraitUpsideDown ||
UIDevice.currentDevice().orientation == UIDeviceOrientation.Unknown) {
return true;
} else {
return false;
}
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.Portrait
}
Since every view controller supports a different orientation, you can do this:
1) In the General tab of your project, select the orientations you need your application to support. for reference click here
2) Now, add the following code in each view controller:
- (UIInterfaceOrientationMask) supportedInterfaceOrientations {
return UIInterfaceOrientationMaskPortrait;
}
Return whichever orientation you want for that specific view controller in this method.
You have to set Xcode settings for handling rotation as following steps for that:
Project> Targets> General> Deployment Info> Device Orientation> (check mark) Portrait
Hope this is helpful to you.
Is there a possibility that I can programatically say that only 1 UIView can be in landscape mode?
My Whole app has to be in portrait mode (not moving at all) but 1 UIView should be able to go in Landscape mode (To show pictures even better);
You rotate VC like this:
- (BOOL)shouldAutorotate {
return self.topViewController.shouldAutorotate;
}
- (NSUInteger)supportedInterfaceOrientations {
return self.topViewController.supportedInterfaceOrientations;
}
Restrict VC so it won't rotate:
- (BOOL)shouldAutorotate { return NO; }
- (NSUInteger)supportedInterfaceOrientations {
return (UIInterfaceOrientationMaskPortrait);
}
You could change condition as per your need and this answer is referred from this link so you could go there for more understanding.
Also do keep that iOS 6/7 have different method for checking.If anything else then let me know.
UPDATED:- iOS 7 callBack method for checking mode
– willRotateToInterfaceOrientation:duration:
– willAnimateRotationToInterfaceOrientation:duration:
– didRotateFromInterfaceOrientation:
I've read almost every post around here regarding my problem but none of the solutions seems to work on my app.
So, I use a custom camera view (with buttons on toolbar and an overlay) that is being presented modally from a view controller. My app only supports landscape left and right for the orientation. And i want to stop the camera view from autorotating when it's being presented. I've put all the methods needed for autorotation on my view controller and my app delegate. I've checked on my plist file too and the supported rotations are correct. But my camera view keeps on rotating to any rotation (portrait and landscape) when I rotate the device, resulting on the overlay and the toolbar being incorrectly positioned. I also can't check on the camera view's orientation because i tried putting NSLog on shouldAutoRotate method, but it doesn't get called at all.
So how can I check the rotation on my custom camera view? And how can I force it to not rotate and stay still?
If my code is needed, I'll post it here. If anyone can help me on it I'll greatly appreciate it because it frustrates me so much right now.
Thank you. Cheers.
Create a new class of "UIImagePickerController" and implement the rotation delegates in the .m file as given,
// For lower iOS versions
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
return ((toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft) || ((toInterfaceOrientation == UIInterfaceOrientationLandscapeRight)));
}
// For iOS version 6.0 and above
- (BOOL)shouldAutorotate {
return YES;
}
- (NSUInteger)supportedInterfaceOrientations {
return (UIInterfaceOrientationMaskLandscape);
}
And make an instance of lets say MyImagePickerController instead of UIImagePickerController, and present it. This will work :)
Create a category for UINavigationController
#interface UINavigationController(autoRotation)
-(BOOL)shouldAutoRotate;
#end
#implementation UINavigationController
-(BOOL)shouldAutoRotate{
return [[self.viewControllers lastobject] shouldAutoRoatate];
}
-(NSUInteger)supportedInterfaceOrientations {
return [[self.viewControllers lastobject] supportedInterfaceOrientations];
}
#end
Implement these two methods in your corresponding view controllers
and return the orientation what u exactly want....
xcode -> file -> new file select cocotouch in the leftpane select objective-c category ->next
select give name Picker category on UIImageImagePickerController from dropdown
import
#interface UIImagePickerController (picker)
-(BOOL)shouldAutoRotate;
-(NSUInteger)supportedInterfaceOrientations;
#end
import "UIImagePickerController+picker.h"
#implementation UIImagePickerController (picker)
-(BOOL)shouldAutoRotate{
return yourOrientation;
}
-(NSUInteger)supportedInterfaceOrientations {
return yourInteger;
}
#end
After this when your device's orientation changed then the method shouldAutoRotate get called from your UINavigationController category at this time you have to find out if cameraview is presented if yes then you have to call shouldAutoRotate of Picker
See the following code
in your view controller's shouldAutoRotate
-(BOOL)shouldAutoRotate{
if([self presentingViewController])// Camera is present
return [instanceOfUIImagePickerController shouldAutoRotate];
return yourOrientaionNeededForThisVC;
}
I have a tab bar application, with many views. Is there a way to know if a particular UIViewController is currently visible from within the UIViewController? (looking for a property)
The view's window property is non-nil if a view is currently visible, so check the main view in the view controller:
Invoking the view method causes the view to load (if it is not loaded) which is unnecessary and may be undesirable. It would be better to check first to see if it is already loaded. I've added the call to isViewLoaded to avoid this problem.
if (viewController.isViewLoaded && viewController.view.window) {
// viewController is visible
}
Since iOS9 it has became easier:
if viewController.viewIfLoaded?.window != nil {
// viewController is visible
}
Or if you have a UINavigationController managing the view controllers, you could check its visibleViewController property instead.
Here's #progrmr's solution as a UIViewController category:
// UIViewController+Additions.h
#interface UIViewController (Additions)
- (BOOL)isVisible;
#end
// UIViewController+Additions.m
#import "UIViewController+Additions.h"
#implementation UIViewController (Additions)
- (BOOL)isVisible {
return [self isViewLoaded] && self.view.window;
}
#end
There are a couple of issues with the above solutions. If you are using, for example, a UISplitViewController, the master view will always return true for
if(viewController.isViewLoaded && viewController.view.window) {
//Always true for master view in split view controller
}
Instead, take this simple approach which seems to work well in most, if not all cases:
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
//We are now invisible
self.visible = false;
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
//We are now visible
self.visible = true;
}
For those of you looking for a Swift 2.2 version of the answer:
if self.isViewLoaded() && (self.view.window != nil) {
// viewController is visible
}
and Swift 3:
if self.isViewLoaded && (self.view.window != nil) {
// viewController is visible
}
For over-full-screen or over-context modal presentation, "is visible" could mean it is on top of the view controller stack or just visible but covered by another view controller.
To check if the view controller "is the top view controller" is quite different from "is visible", you should check the view controller's navigation controller's view controller stack.
I wrote a piece of code to solve this problem:
extension UIViewController {
public var isVisible: Bool {
if isViewLoaded {
return view.window != nil
}
return false
}
public var isTopViewController: Bool {
if self.navigationController != nil {
return self.navigationController?.visibleViewController === self
} else if self.tabBarController != nil {
return self.tabBarController?.selectedViewController == self && self.presentedViewController == nil
} else {
return self.presentedViewController == nil && self.isVisible
}
}
}
You want to use the UITabBarController's selectedViewController property. All view controllers attached to a tab bar controller have a tabBarController property set, so you can, from within any of the view controllers' code:
if([[[self tabBarController] selectedViewController] isEqual:self]){
//we're in the active controller
}else{
//we are not
}
I made a swift extension based on #progrmr's answer.
It allows you to easily check if a UIViewController is on screen like so:
if someViewController.isOnScreen {
// Do stuff here
}
The extension:
//
// UIViewControllerExtension.swift
//
import UIKit
extension UIViewController{
var isOnScreen: Bool{
return self.isViewLoaded() && view.window != nil
}
}
For my purposes, in the context of a container view controller, I've found that
- (BOOL)isVisible {
return (self.isViewLoaded && self.view.window && self.parentViewController != nil);
}
works well.
I use this small extension in Swift 5, which keeps it simple and easy to check for any object that is member of UIView.
extension UIView {
var isVisible: Bool {
guard let _ = self.window else {
return false
}
return true
}
}
Then, I just use it as a simple if statement check...
if myView.isVisible {
// do something
}
I hope it helps! :)
Good point that view is appeared if it's already in window hierarchy stack.
thus we can extend our classes for this functionality.
extension UIViewController {
var isViewAppeared: Bool { viewIfLoaded?.isAppeared == true }
}
extension UIView {
var isAppeared: Bool { window != nil }
}
XCode 6.4, for iOS 8.4, ARC enabled
Obviously lots of ways of doing it. The one that has worked for me is the following...
#property(nonatomic, readonly, getter=isKeyWindow) BOOL keyWindow
This can be used in any view controller in the following way,
[self.view.window isKeyWindow]
If you call this property in -(void)viewDidLoad you get 0, then if you call this after -(void)viewDidAppear:(BOOL)animated you get 1.
Hope this helps someone. Thanks! Cheers.
if you're utilizing a UINavigationController and also want to handle modal views, the following is what i use:
#import <objc/runtime.h>
UIViewController* topMostController = self.navigationController.visibleViewController;
if([[NSString stringWithFormat:#"%s", class_getName([topMostController class])] isEqualToString:#"NAME_OF_CONTROLLER_YOURE_CHECKING_IN"]) {
//is topmost visible view controller
}
The approach that I used for a modal presented view controller was to check the class of the presented controller. If the presented view controller was ViewController2 then I would execute some code.
UIViewController *vc = [self presentedViewController];
if ([vc isKindOfClass:[ViewController2 class]]) {
NSLog(#"this is VC2");
}
I found those function in UIViewController.h.
/*
These four methods can be used in a view controller's appearance callbacks to determine if it is being
presented, dismissed, or added or removed as a child view controller. For example, a view controller can
check if it is disappearing because it was dismissed or popped by asking itself in its viewWillDisappear:
method by checking the expression ([self isBeingDismissed] || [self isMovingFromParentViewController]).
*/
- (BOOL)isBeingPresented NS_AVAILABLE_IOS(5_0);
- (BOOL)isBeingDismissed NS_AVAILABLE_IOS(5_0);
- (BOOL)isMovingToParentViewController NS_AVAILABLE_IOS(5_0);
- (BOOL)isMovingFromParentViewController NS_AVAILABLE_IOS(5_0);
Maybe the above functions can detect the ViewController is appeared or not.
If you are using a navigation controller and just want to know if you are in the active and topmost controller, then use:
if navigationController?.topViewController == self {
// Do something
}
This answer is based on #mattdipasquale's comment.
If you have a more complicated scenario, see the other answers above.
you can check it by window property
if(viewController.view.window){
// view visible
}else{
// no visible
}
I needed this to check if the view controller is the current viewed controller, I did it via checking if there's any presented view controller or pushed through the navigator, I'm posting it in case anyone needed such a solution:
if presentedViewController != nil || navigationController?.topViewController != self {
//Viewcontroller isn't viewed
}else{
// Now your viewcontroller is being viewed
}
Window:
window.isVisible
viewController.view.window?.isVisible ?? false
View (macOS):
extension NSViewController {
var isOnScreen: Bool {
return ( self.isViewLoaded && view.window != nil )
}
}