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)
Related
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.
I am trying to incorporate some 3D touch into an application and I've run into a weird issue where the forceTouchCapability check is returning nil on viewDidLoad but not in viewWillAppear/viewDidAppear.
I'm aware that this is only available on iOS 9+ so I've added checks to verify that the traitCollection property on the view controller responds to forceTouchCapability as in the following:
- (void)loadView {
self.view = [[MyView alloc] init];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Checking the force touch availability here
if ([self.traitCollection respondsToSelector:#selector(forceTouchCapability)] &&
self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable) {
// This won't get called because forceTouchCapability is returning nil
// which corresponds to UIForceTouchCapabilityUnknown
[self registerForPreviewingWithDelegate:self sourceView:self.view];
}
}
In LLDB with a breakpoint at the if statement, entering po [self.traitCollection forceTouchCapability] returns nil which corresponds to UIForceTouchCapabilityUnknown. However, the traitCollection itself is not nil.
According to the documentation for UIForceTouchCapabilityUnknown:
UIForceTouchCapabilityUnknown: The availability of 3D Touch is unknown. For example, if you create a view but have not yet added it to your app’s view hierarchy, the view’s trait collection has this value.
Has the view not been added to the hierarchy by this point?
I'm curious if anyone has run into this issue before and how to work around this? I would like to avoid adding this in the viewDidAppear as this can get called quite a bit.
If it helps, I'm running this on a 6S on iOS 9.1 with Xcode 7.2
The view hasn't been added to the View Hierarchy yet. You can see this easily by checking for a superview in the debug console
(lldb) po self.view.superview
nil
If that's what you're seeing, the view hasn't been added to a hierarchy yet: so you have to put your check elsewhere.
This is kind of confusing because in Apple's ViewControllerPreview sample app it's in viewDidLoad. But it really should in traitCollectionDidChange:, because then you're sure that the view has been added to the app's hierarchy.
This is the code I use (works on iOS 8, if you don't need to support that feel free to move the outer conditional).
- (void)traitCollectionDidChange:(UITraitCollection *)previousTraitCollection {
[super traitCollectionDidChange:previousTraitCollection];
if ([self.traitCollection respondsToSelector:#selector(forceTouchCapability)]) {
if (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable) {
// retain the context to avoid registering more than once
if (!self.previewingContext) {
self.previewingContext = [self registerForPreviewingWithDelegate:self sourceView:self.view];
}
} else {
[self unregisterForPreviewingWithContext:self.previewingContext];
self.previewingContext = nil;
}
}
}
The added benefit to this is that your view will be registered/unregistered if the user changes their 3D Touch settings while the app is running.
I've also seen this issue, and found that the easiest way to check whether the device can support force touch or not is doing it via the screen instance. This kinda makes sense because the capability is a property of the screen. Doing it this way means you don't have to worry about the lifecycle of a viewcontroller or a view.
func canForceTouch() -> Bool
{
if iOS9OrHigher // pseudocode, a function that makes sure u only do this check on ios9 or higher
{
return UIScreen.mainScreen().traitCollection.forceTouchCapability == .Available
}
return false
}
Like what #bpapa said, Your view hasn't added to view hierarchy yet, But my solution is different little bit:
var token:dispatch_once_t = 0
override func viewDidAppear(animated: Bool) {
dispatch_once(&token) {
// Force Touch Checking
if #available(iOS 9.0, *) {
if self.traitCollection.forceTouchCapability == .Available {
self.registerForPreviewingWithDelegate(self, sourceView: self.view)
}
}
}
}
I am facing problem in view orientation in my app.
Like
I have two view controller, VC1 and VC2
VC1 have fix landscape orientation.
VC2 have both
VC1 -> VC2 is fine. means when I go from VC1 to VC2, VC2 change its orientation in both landscape and portrait.
But when I comeback to VC1 from VC2(where VC2 in portrait mode), VC1 also is in portrait mode but I want VC1 is in landscape only irrespective of VC2 mode.
Please guys help me. Seeking solution from last 2 days.
Thanks in advance.
Refer below link for solution
http://swiftiostutorials.com/ios-orientations-landscape-orientation-one-view-controller/
In your VC1..
-(BOOL)shouldAutorotate
{
return NO;
}
-(NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskLandscapeLeft;
}
Hope it helps you...
First of all, write this in AppDelegate.m
- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
return (UIInterfaceOrientationMaskAll);
}
Then, For VC1, in which landscape orientation, write this:
- (BOOL)shouldAutorotate
{
return YES;
}
- (NSUInteger)supportedInterfaceOrientations
{
return (UIInterfaceOrientationMaskPortrait);
}
For VC2, which have both, change masking to All.
- (NSUInteger)supportedInterfaceOrientations
{
return (UIInterfaceOrientationMaskAllButUpsideDown);
//OR return (UIInterfaceOrientationMaskAll);
}
1. Enable all orientation support for project.
For VC1 Add this line VC1Controller Class
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskLandscape;
}
For VC2 Add this in VC2Controller Class
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskAll;
}
basically the view-controller-based orientation support in an iOS app is a piece of cake – I did the code in Swift, but ObjC concept would be totally identical to this.
I have created a quick tutorial with UINavigationController but you can convert that to UITabBarController by keeping the concept but updating the environment slightly.
step-1
initially set the orientation support for your app like this:
step-2
create a simple UINavigationController-based storyboard like this:
NOTE: don't worry if it does not say initially OrientaionSupporterController (bonus point if you'd spot the consistent typo here!), I will cover that just in the very next step.
step-3
create a subset of the navigation-controller, like this:
import UIKit
// MARK: - Implementation
class OrientaionSupporterController: UINavigationController {
// MARK: - Active View Controller
private var activeViewController: UIViewController? {
get {
return self.presentedViewController ?? self.topViewController // for possible modal support
}
}
// MARK: - Orientations
override var shouldAutorotate: Bool {
get {
return self.activeViewController?.shouldAutorotate ?? true // yes, rotate it, please
}
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return self.activeViewController?.supportedInterfaceOrientations ?? .all // default is all possible orientations
}
}
then make sure the that becomes the base class in IB as well:
step-3
create the individual view-controllers with custom orientation support, like e.g. with only portrait and landscape-left support:
import UIKit
// MARK: - Implementation
class ViewController: UIViewController {
// MARK: - Orientation
override var shouldAutorotate: Bool {
get {
return true
}
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return [.portrait, .landscapeLeft] // no one find that preactical but works flawlessly
}
}
NOTE: you can convert this tutorial anytime with UITabBarController, you just need to (obviously) create a subset of the tab-bar-controller and use the selectedViewController to get the currently visible one.
NOTE#2: obviously you can go much further on this way and you can nest the customised navigation-controllers in the view hierarchy, or if you have multiple UIWindow instances in the queue and override the supported orientations there as well for each individual windows (e.g. some support all four orientations, while some other windows does only landscape for e.g. video playback, etc...)
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 am new to Objective c Native coding in IOS. I am having two buttons. One to lock the app to portrait and another lock the landscape orientation. What should I do to achieve this. Locking in the sense it will fix to the locked side and will not turn.
Yes i have used a method to implement the same using ios plugin which i created in worklight(For hybrid apps).
The function for setting the flag is
#import "HelloworlPlugin.h"
#implementation HelloworlPlugin
int count=0;
-(void)sayhello:(NSMutableArray *)arguments withDict:(NSMutableDictionary *)option
{
[arguments pop];
NSString *responseString=[NSString stringWithFormat:#"%#",[arguments objectAtIndex:0]];
if([responseString isEqualToString:#"1"])
{
count=1;
}
else
{
count=0;
}
NSLog(#"Zero %#",responseString);
}
-(int)count1
{
NSLog(#"count= %d",count);
if(count<1)
{
Cv=0;
}
else
{
Cv=1;
}
NSLog(#"%d",Cv);
return Cv;
}
#end
Where in say hello function i get the arguments from the hybrid app and based on that i set the flag variable Cv to 1 or 0.
Below is the default method which i have changed little bit to do my implementation
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
HelloworlPlugin *object=[[HelloworlPlugin alloc] init];
int fValue=[object count1];
NSLog(#"%d",fValue);
if(fValue==1)
{
return (interfaceOrientation ==UIInterfaceOrientationPortrait);
}
else
{
return true;
}
}
shouldAutorotateToInterfaceOrientation
is a thing that is default function based on which the orientation is set returning true set all the orientation else by giving the approriate orientation we can set the answer.So here based on the cv value i stored in fValue i have locked the orientation.
For example this way:
[[UIApplication sharedApplication] setStatusBarOrientation:UIDeviceOrientationLandscapeLeft animated:NO];