Image moves down after capturing using ImagePicker Controller in iOS8 - ios

I have placed an overlay image over camera view and trying to Capture the image but as soon as I capture the image (I have not tapped the "Use Photo" button yet), the captured image moves some pixel down and the height of top black bar having flash and front/back camera settings buttons suddenly increases. So the situation now is - my overlay image has not moved a single pixel and the captured image has moved downwards. So I am not able to capture the correct image with overlay placed properly. This issue is only in iOS8 and above.
Anybody facing this issue on iOS8 ??

It turns out that for the iPhone (when the UImagePickerController is presented under a navigation controller) the navigation bar is hidden when you take a picture. In the following preview, however, the navigation bar is no longer hidden even if it's not visible and unhiding moves the preview image down or to the right, depending on the orientation. To compensate for this change you'll have to adjust the origin of the camera overlay view accordingly. I resolved this by adding a callback that handles the UIImagePickerController notifications. In your code where you initiate the UIImagePickerController add the following code:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(handleImagePickerNotification:)
name:#"_UIImagePickerControllerUserDidCaptureItem"
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(handleImagePickerNotification:)
name:#"_UIImagePickerControllerUserDidRejectItem"
object:nil];
The callback which handles the notification must distinguish between the UserDidCaptureItem and UserDidRejectItem notifications. In the first case the x- or y-origin of the camera overlay frame is incremented (depending on the orientation), in the second case the increment is reverted again. The size of the increment or decrement is the height of the navigation bar.
- (void)handleImagePickerNotification:(NSNotification *)notification {
// This notification compensates for a feature (?) introduced with iOS 8 that moves the
// image after it's been taken with the UIImagePickerController.
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
CGRect frame = cameraOverlay.frame;
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
CGFloat barHeight = [self.navigationController navigationBar].frame.size.height;
if ([[notification name] isEqualToString:#"_UIImagePickerControllerUserDidCaptureItem"]) {
if (UIInterfaceOrientationIsLandscape(orientation))
frame.origin.x += barHeight;
else
frame.origin.y += barHeight;
} else
if ([[notification name] isEqualToString:#"_UIImagePickerControllerUserDidRejectItem"]) {
if (UIInterfaceOrientationIsLandscape(orientation))
frame.origin.x -= barHeight;
else
frame.origin.y -= barHeight;
[cameraOverlay setFrame:frame];
}
[cameraOverlay setFrame:frame];
}
This isn't a very elegant way of resolving the issue but in my case it worked.

Related

How to keep UIView's size when toggle in call status bar [duplicate]

I have an iOS app. It works great.
Except when the user has a hotspot on or is in a call but the call app is minimised
The extended height of the status bar pushes my ui down, making part of it disappear,
at the bottom.
I want this extended bar to overlay the top of the screen and not push the ui downwards.
How do I achieve that ?
The Simplest Solution is to make sure that your view's springs-and-struts or Autolayout properties allow for compression or expansion of the view , If you have some complex UI then you can implement UIApplicationWillChangeStatusBarFrameNotification observer.
You can handle the UIApplicationWillChangeStatusBarFrameNotification and UIApplicationDidChangeStatusBarOrientationNotification notifications which will tell you the new size of the status bar.
If you are intent on using a transform on your view to handle resizing, you can implement -viewWillLayoutSubviews in your view controllers (probably in a common base class) to set a transform on the root view of the view controller.
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(statusFrameChanged:)
name:UIApplicationWillChangeStatusBarFrameNotification
object:nil];
}
-(void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIApplicationWillChangeStatusBarFrameNotification
object:nil];
}
- (void)statusFrameChanged:(NSNotification*)note
{
CGRect statusBarFrame = [note.userInfo[UIApplicationStatusBarFrameUserInfoKey] CGRectValue];
CGFloat statusHeight = statusBarFrame.size.height;
UIScreen *screen = [UIScreen mainScreen];
CGRect viewRect = screen.bounds;
viewRect.size.height -= statusHeight;
viewRect.origin.y = statusHeight;
self.view.frame = viewRect;
[self.view setNeedsLayout];
}
- (void)viewWillLayoutSubviews
{
[super viewWillLayoutSubviews];
CGRect baseFrame = self.view.frame;
// 548.0 is the full height of the view. Update as necessary.
CGFloat scale = self.view.frame.size.height / 548.0;
[self.view setTransform:CGAffineTransformMakeScale(1.0, scale)];
self.view.frame = baseFrame;
}
I used use "Vertical space - Bottom layout Guide - Button". This way, a button I have on the bottom of the screen stays in the same place when there is an in call bar and if a different screen size is used (3.5inch or 4icnh).

Should I expect inconsistencies in screen dimensions between iPhones and iPads after orientation changes?

On iOS 9.3 iPhones and iPads (actual devices and in the simulator), I am getting inconsistent information (between the device and the simulator) about the [UIScreen mainScreen].bounds after an orientation change notification.
My view controller adds a notification for orientation changes when the view loads:
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(deviceOrientationDidChangeNotification:)
name:UIDeviceOrientationDidChangeNotification
object:nil];
The behaviour when the orientation changes is as follows:
- (void) deviceOrientationDidChangeNotification:(NSNotification *) notification {
CGRect frame = [UIScreen mainScreen].bounds;
NSLog(#"Main screen is w=%f h=%f", frame.size.width, frame.size.height);
}
Running this on an iPhone, after the orientation changes, the log message indicates a frame width and height that correspond with the post orientation change screen dimensions.
Running this on an iPad, after the orientation changes, the log message indicates a frame width and height that correspond with the pre orientation change screen dimensions.
Is this kind of inconsistency something that needs to be coded around? I could start trying to detect what the orientation is (landscape or portrait) and then using the width and height values that make sense but that is pretty hacky.
The right way to handle this is to avoid the notification system, instead using the
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id)coordinator
method on the UIViewController where you want to adapt the UI for an orientation change.

Handling rotation and adjusting views programmatically (Xcode)

Here is the problem I've been struggling with:
I'm creating a view programatically using loadView.
Once it's loaded it looks just great in Portrait view. However, I want to handle rotation of the device. Therefore I use willAnimateRotationToInterfaceOrientation method.
Within this method I call a function that adjust all the elements. What that function does is just goes through all my views and sets new CGRect to each of them. It works just fine on portrait orientations (up and upside-down), but once I change orientation to horizontal, it crops.
Two questions:
What is the most likely reason for such behavior?
How would you suggest handling device rotation without creating a separate view for horisontal / vertical orientations?
I think you are missing the key part. When you are setting the frame at portrait view at view did load, view got the frame but when it change to the landscape it change but again from there i think you are not setting the frame for portrait view. use notification
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(orientationChanged:) name:#"UIDeviceOrientationDidChangeNotification" object:nil];
-(void) orientationChanged:(NSNotification *)notification
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
UIDeviceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
if((orientation == UIDeviceOrientationPortrait) || (orientation == UIDeviceOrientationPortraitUpsideDown)) {
// set frame here
}else if ((orientation == UIDeviceOrientationLandscapeLeft) || (orientation == UIDeviceOrientationLandscapeRight)){
// set frame here too
}
}];
}

Is it possible to access properties of an iOS system animation?

Is it possible to get the animation properties (speed and easing curve) for a built in iOS system animation? Specifically, the UIStatusBarAnimationSlide when you hide or show the status bar. Right now I'm just eyeballing it and have come up with a good match: .35 seconds using the default animation curve. This works fine, but Apple is liable to change an animation like this in a future iOS update and it would be nice to match it exactly and not rely on hard-coded values I came up with myself.
For what it's worth, here is the method my view controller is calling when I tap the view to hide the status bar and resize the view to fill the screen.
-(void)tappedView:(UIGestureRecognizer *)gestureRecognizer
{
UIApplication *app = [UIApplication sharedApplication];
// First, toggle the visibility of the status bar
[[UIApplication sharedApplication] setStatusBarHidden:![app isStatusBarHidden] withAnimation:UIStatusBarAnimationSlide];
// Then scale this view controller's view, attempting to match the built-in
// UIStatusBarAnimationSlide animation
[UIView animateWithDuration:.35
animations:^{
self.view.frame = [UIScreen mainScreen].applicationFrame;
}];
}
As an aside, I'm surprised I couldn't find a built in way to handle resizing a VC's view when the status bar is hidden. After all, if the status bar doubles its height when a call is in progress, the view resizes automatically. Tell me I'm missing something and there's a way to get the view to grow automatically, too.
Here's a chuck of code I use in my app:
- (void)application:(UIApplication *)application willChangeStatusBarFrame:
(CGRect)oldStatusBarFrame {
[UIView animateWithDuration:0.355f animations:^{
if(floating_point_values_are_equal(oldStatusBarFrame.size.height, 20.0f)) {
for(UIViewController* VC in self.tabBarController.viewControllers) {
UIView* view = VC.view;
[view setTransform:CGAffineTransformMakeScale(1.0f, 1.0f)];
}
} else {
for(UIViewController* VC in self.tabBarController.viewControllers) {
UIView* view = VC.view;
CGFloat ratio = (view.frame.size.height - 20) / view.frame.size.height;
[view setTransform:CGAffineTransformMakeScale(1.0f, ratio)];
}
}
}];
}
It basically scales the entire app depending on the new screen dimensions. It only works because the scale ratio is not a big change- doing this for the new iPhone screen would not look right.

UIView atop the Keyboard similar to iMessage App

currently I'm attempting to basically implement and exact copy of Apples iMessage App.
That means I need a UITextView that is docked at the bottom of the screen, and moves up when it becomes firstResponder. - That's pretty easy actually. There's a bazillion ways to do that and two of the most common are of course animating the view upwards or downwards if a notification was received. The other is to do it via the inputAccessoryView. Sadly some of the features the one has, the other doesn't. And they seem to be mutually exclusive.
The big problem is rotation.
I've digged through roughly at least seven different github projects, all of them re-implementing the same functionality/behavior, that I'm trying to achieve, but literally all of them failing miserably.
HPGrowingTextView for instance, which the official Facebook/FacebookMessenger/(and possibly WhatsApp) Apps makes use of, is one big piece of junk-code. Take your iDevice, open the Facebook App, go the the Chat, pop the keyboard and rotate your device. If you pay attention you'll notice the input-bar jumping slightly and leaving some blank space between the keyboard's frame and its own. Then take a look at Apples implementation in iMessage when the keyboard is shown. It's perfect.
Other than that the contentOffset and EdgeInset-hacking that the HPGrowingTextView library makes use of gives me nightmares.
So I wanted to do it myself and start from scratch.
Right now I've got a very slick, elegant and hack-less implementation of a growing UITextView, but one part is missing.
Elegant rotation.
When I simply adjust the frames to their respective new positions in the willRotateToInterfaceOrientation:duration: method, everything ends up working perfectly BUT I have the same problem that HPGrowingTextView(see Facebook App) has. A litte bit of space between the inputview and the keyboard while the rotation takes place.
I found out that when rotating the device to landscape, the portrait keyboard which is currently shown does not "morph" but rather disappears (sends the 'willHide' notification) and a landscape version reappears (sending the 'willShow' notification). The transition is a very subtle fade and possibly some resizing.
I re-implemented my project using the inputAccessoryView to see what happens then and I was pleasantly surprised. The inputAccessoryView rotates in perfect sync with the keyboard. There's no space/gap between the two.
Sadly I have yet to come up with an idea how to have the inputAccessoryView dock to the bottom of the screen and NOT disappear/move out of it alongside the keyboard...
What I don't want are hack-y solutions like,..."lowering the frame slightly in the toInterfaceOrientation's CoordinateSystem and then moving it back up when the didRotateFrom... was called."
I know of one other app that has managed to implement such behavior and it's the "Kik Messenger".
Does anyone have an idea, advice or a link that I haven't seen yet covering that topic?
Thanks a bunch!
Note: Once this problem is solved I will open source the project for everyone to profit because almost every implementation I was able to find over the course of the past few days, is a mess.
I recently ran into the same problem, and had to build out a custom solution as I wasn't entirely happy with the available 3rd party libraries. I've split out this implementation into it's own GitHub project:
MessageComposerView
From some simple testing on iOS 6.1 7 & 8 simulators the rotations seem to properly follow the keyboard. The view will also grow with text and resize automatically on rotation.
You can use a very basic init function like so to create it with screen width and default height e.g.:
self.messageComposerView = [[MessageComposerView alloc] init];
self.messageComposerView.delegate = self;
[self.view addSubview:self.messageComposerView];
There are several other initializers that are also available to allow you to customize the frame, keyboard offset and textview max height. See readme for more!
I have been successful at solving the problem in quite an elegant manner (I think,...).
The code will be released on Github next week and linked to in this answer.
--
How it's done: I made the rotation work by choosing the inputAccessoryView-way of doing it.
Nomenclature:
'MessageInputView' is a UIView containing my 'GrowingUITextView' (it also contains a "Send" Button and the background image).
'ChatView' is the view that belongs to the ChatViewController that displays all the Chatbubbles and has my 'MessageInputView' docked at the bottom.
'keyboardAccessoryView' is an empty UIView sized: CGRect(0,0,0,0).
I needed to figure out how to have the MessageInputView stick around on the screen when the keyboard was dismissed. That was the tricky part. I did this by creating another view (keyboardAccessoryView) and had my GrowingUITextView use it as its inputAccessoryView. I retained the keyboardAccessoryView because I'd need the reference to it later on.
Then I remembered some of the stuff I did in my other attempt (animating the MessageInputView's frames around the screen whenever a keyboard notification arrived).
I added my MessageInputView as a subview to my ChatView (at the very bottom). Whenever it is activated and the willShow: methods is called by a keyboard notification, I manually animate the MessageInputView's frame to it's designated position up top. When the animation finishes and the completion block executes I remove the subview from the ChatView and add it to the keyboardAccessoryView. This causes another notification to be fired off because the keyboard is re-loaded EVERY time the inputAccessoryView's frame/bounds are changed!. You need to be aware of that and handle it appropriately!
When the keyboard is about to dismissed, I convert my MessageInputView's frame to my ChatView's coordinate system and add it as a subview. Thus it is removed from my keyboardAccessoryView. I then resize the keyboardAccessoryView's frame back to CGRect(0,0,0,0) because otherwise the UIViewAnimationDuration will not match! Then I allow the keyboard to be dismissed and I have my MessageInputView follow it from above and eventually dock at the bottom of the screen.
This is quite a lot of work for very little gain though.
--
Take care.
PS: If someone figures out an easier way to do it (perfectly) let me know.
Here's a UITextView subclass that is working properly on iOS 9.3.1 and 8.3.1. It takes care of growing and shrinking with limits, while keeping the caret always in the right place and animating smoothly.
Sticking the view over the keyboard is trivial, with many solutions to be found easily, so it's not covered...
I could not find any made-solutions that were production ready so I ended up working on this from scratch. I had to work out a lot of little problems along the way.
Code comments should give you an idea of what's going on.
I have shared this on my Github, Contributions greatly appreciated.
Notes
Not tested to support landscape
Not tested on i6+
Demo
(after max height element becomes scrollable. Forgot to drag the demo, but this is working as expected as well... )
Subclass
class ruuiDynamicTextView: UITextView {
var dynamicDelegate: ruuiDynamicTextViewDelegate?
var minHeight: CGFloat!
var maxHeight: CGFloat?
private var contentOffsetCenterY: CGFloat!
init(frame: CGRect, offset: CGFloat = 0.0) {
super.init(frame: frame, textContainer: nil)
minHeight = frame.size.height
//center first line
let size = self.sizeThatFits(CGSizeMake(self.bounds.size.width, CGFloat.max))
contentOffsetCenterY = (-(frame.size.height - size.height * self.zoomScale) / 2.0) + offset
//listen for text changes
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(textChanged), name: UITextViewTextDidChangeNotification, object: nil)
//update offsets
layoutSubviews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
//Use content size if more than min size, compensate for Y offset
var height = max(self.contentSize.height - (contentOffsetCenterY * 2.0), minHeight)
var updateContentOffsetY: CGFloat?
//Max Height
if maxHeight != nil && height > maxHeight {
//Cap at maxHeight
height = maxHeight!
} else {
//constrain Y to prevent odd skip and center content to view.
updateContentOffsetY = contentOffsetCenterY
}
//update frame if needed & notify delegate
if self.frame.size.height != height {
self.frame.size.height = height
dynamicDelegate?.dynamicTextViewDidResizeHeight(self, height: height)
}
//constrain Y must be done after setting frame
if updateContentOffsetY != nil {
self.contentOffset.y = updateContentOffsetY!
}
}
func textChanged() {
let caretRect = self.caretRectForPosition(self.selectedTextRange!.start)
let overflow = caretRect.size.height + caretRect.origin.y - (self.contentOffset.y + self.bounds.size.height - self.contentInset.bottom - self.contentInset.top)
if overflow > 0 {
//Fix wrong offset when cursor jumps to next line un explisitly
let seekEndY = self.contentSize.height - self.bounds.size.height
if self.contentOffset.y != seekEndY {
self.contentOffset.y = seekEndY
}
}
}
}
protocol ruuiDynamicTextViewDelegate {
func dynamicTextViewDidResizeHeight(textview: ruuiDynamicTextView, height: CGFloat)
}
How I fix this problem for me:
I have ChatViewController and FooterViewController as UIContainerView. Also, I have contentView outlet in FooterViewController. Then in ChatViewController I have:
override func becomeFirstResponder() -> Bool {
return true
}
override var inputAccessoryView: UIView? {
if let childViewController = childViewControllers.first as? FooterViewController {
childViewController.contentView.removeFromSuperview()
return childViewController.contentView
}
return nil
}
Another way is to create view programmatically and return as inputAccessoryView.
Recently I've wrote a blog post about this exact problem you've described and how to solve it with a short and elegant way by using keyboard notifications but without using the inputAccessoryView. And although this question is pretty old this topic is still relevant so here is the link to the post: Synchronizing rotation animation between the keyboard and the attached view
If you don't want to dive into the long explanation described in the blog post here is a short description with a code example:
The basic principle is to use the same method that everyone uses - observing keyboard notifications to animate the attached view up and down. But in addition to that, you have to cancel these animations when the keyboard notifications are fired as a consequence of interface orientation change.
Rotation example without animation cancellation custom on interface orientation change:
Rotation example with animation cancellation on interface orientation change:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter]
addObserver:self selector:#selector(adjustViewForKeyboardNotification:)
name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter]
addObserver:self selector:#selector(adjustViewForKeyboardNotification:)
name:UIKeyboardWillHideNotification object:nil];
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[[NSNotificationCenter defaultCenter]
removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter]
removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
[super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
self.animatingRotation = YES;
}
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
[super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
self.animatingRotation = NO;
}
- (void)adjustViewForKeyboardNotification:(NSNotification *)notification {
NSDictionary *notificationInfo = [notification userInfo];
// Get the end frame of the keyboard in screen coordinates.
CGRect finalKeyboardFrame = [[notificationInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
// Convert the finalKeyboardFrame to view coordinates to take into account any rotation
// factors applied to the window’s contents as a result of interface orientation changes.
finalKeyboardFrame = [self.view convertRect:finalKeyboardFrame fromView:self.view.window];
// Calculate new position of the commentBar
CGRect commentBarFrame = self.commentBar.frame;
commentBarFrame.origin.y = finalKeyboardFrame.origin.y - commentBarFrame.size.height;
// Update tableView height.
CGRect tableViewFrame = self.tableView.frame;
tableViewFrame.size.height = commentBarFrame.origin.y;
if (!self.animatingRotation) {
// Get the animation curve and duration
UIViewAnimationCurve animationCurve = (UIViewAnimationCurve) [[notificationInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
NSTimeInterval animationDuration = [[notificationInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
// Animate view size synchronously with the appearance of the keyboard.
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:animationDuration];
[UIView setAnimationCurve:animationCurve];
[UIView setAnimationBeginsFromCurrentState:YES];
self.commentBar.frame = commentBarFrame;
self.tableView.frame = tableViewFrame;
[UIView commitAnimations];
} else {
self.commentBar.frame = commentBarFrame;
self.tableView.frame = tableViewFrame;
}
}

Resources