i'm working on a project where i have a tableview and a uitextfield.
I'm applying the following method when the uitextfield gain/loose the focus :
-(void)enableInset {
CGFloat offSet = -30.0f;
UIEdgeInsets inset = UIEdgeInsetsMake(placesMapView.frame.size.height - offSet, 0.0f, 0.0f, 00.f);
// Updating the tableView position.
placesTableView.contentInset = inset;
placesTableView.contentOffset = CGPointMake(0.0f, -(placesMapView.frame.size.height - offSet));
placesTableView.scrollIndicatorInsets = inset;
}
and
- (void)disableInset {
CGFloat offset = self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height;
UIEdgeInsets inset = UIEdgeInsetsMake(offset, 0.0f, 0.0f, 00.f);
placesTableView.contentInset = inset;
placesTableView.contentOffset = CGPointMake(0.0f, -offset);
placesTableView.scrollIndicatorInsets = inset;
}
The enableInset method is called in viewDidLayoutSubviews.
then when i call disableInset and enableInset, the UITableView can not be scrolled anymore.
What did i did wrong ? Any idea where i can look for some answer ?
EDIT :
If it can help, i added the project on github :
https://github.com/Loadex/PlaceViewer
To re-produce the bug :
Scroll the list, tap on the search bar, hit cancel, try to scroll again the list.
Weirdly click on the filter button, when the UIActionSheet is dismissed, the scroll is working again.
While looking for a solution to your problem i noticed that the bottom part of the contentInset of your placesTableView kept changing through the different states. It was 0 when in the initial state where you could see the map, and the tableView was behaving as expected. It got set to 216 when the keyboard came up after tapping the search field. I figured this was some automated communication between the tableView and the keyboard (through Notifications or something you did in PlacesQueryTableViewController). This is fine because we want the bottom inset to be set to the top of the keyboard when it appears. Now, here comes the buggy part. When I tapped the cancel button, the contentInset.bottom got set to -216.
I can't quite explain why this happens, but I suspect it has something to do with how that automatic change of the inset is implemented. I suspect that it does something like tableView.contentInset.bottom -= heightOfKeyboard, and that probably happens when the animation is finished, and not before. The source of your problem is that you change that bottom of contentInset before the animation is done, and thus before that automatic change has happened. So you're setting the bottom to 0 as soon as the user taps cancel. Then the system comes in and reduces it by the height of the keyboard, which turns out to be 216. That's what I think is happening anyway.
To fix this problem, avoid changing the bottom part of the contentInset and just change the top part. placesTableView.contentInset.top is readOnly, but if you do it like in the code below, you can get around that. I have just changed two lines of code in each method, the ones that have to do with the inset. Hopefully you see what I did.
-(void)enableInset {
NSLog(#"Enabling insets");
// Setting the tableView to overlay the map view
CGFloat offSet = [placestableViewController tableView:placestableViewController.tableView heightForRowAtIndexPath:nil] - 30.0f;
UIEdgeInsets inset = placesTableView.contentInset; // UIEdgeInsetsMake(placesMapView.frame.size.height - offSet, 0.0f, 0.0f, 0.0f);
inset.top = placesMapView.frame.size.height - offSet;
// Updating the tableView position.
placesTableView.contentInset = inset;
placesTableView.contentOffset = CGPointMake(0.0f, -(placesMapView.frame.size.height - offSet));
placesTableView.scrollIndicatorInsets = inset;
placesMapView.hidden = NO;
[placestableViewController loadObjects];}
- (void)disableInset {
NSLog(#"Disable insets");
CGFloat offset = self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height;
UIEdgeInsets inset = placesTableView.contentInset;// UIEdgeInsetsMake(offset, 0.0f, 0.0f, 0.0f);
inset.top = offset;
placesTableView.contentInset = inset;
placesTableView.contentOffset = CGPointMake(0.0f, -offset);
placesTableView.scrollIndicatorInsets = inset;
// Hidding the map while in search
placesMapView.hidden = YES;}
.
BTW, if you want to know how I found the contentInset values at the different states, it's quite simple. What I did was to set myself as the delegate of placesTableView in - (void)viewDidLoad like this placesTableView.delegate = self;. I also had to change the #interfacestatement to #interface KrackMapViewController () <UITableViewDelegate> to say that we conform to the UITableViewDelegate. Now, here's the trick: UITableViewDelegate conforms to UIScrollViewDelegate. That means we can implement methods of the scroll view delegate. The one that is particularly interesting is this one:
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
NSLog(#"Did scroll with insetTop: %f, insetBottom: %f, contentOffset: %f", placesTableView.contentInset.top,
placesTableView.contentInset.bottom,
placesTableView.contentOffset.y);
}
That lets us know when you start dragging the tableView, and in there simply NSLog out the different parameters.
I hope this was helpful. Let me know if this works for you.
After a few research here is what I noticed:
The TableView when the keyboard is released is not scrolling because the tableview seems to believe that it is displayed on the entire screen. I tried to add more data in the tableview and we can see that the view is scrolling a little.
What I believe happened is that when the keyboard is hidden, some automatic calls are done and messing with what I set in my enableInset method. Here is my working solution:
I registered for the hideKeyboard event:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(keyboardDidHide:)
name:UIKeyboardDidHideNotification
object:nil];
and in the callback I called enableInset:
- (void)keyboardDidHide: (NSNotification *) notif{
[self enableInset];
}
And the view is scrolling back again.
Any explanation about this are welcome.
Related
In my main view controller, I present a popup which is a UITableviewcontroller class and has a resizable textview as one of the cells. Now as the content grows and text view expands the typing content goes beyond the keyboard and it's not visible on the screen. In order to resolve this issue, I calculated the cursor position and keyboard position and based on that adjusted the tableviews content offset so that when typing starts the offset adjust to show the typing content above the keyboard. It seems to work but as per my logic now the issue is when there's a large content and if the cursor is at the bottom and if you scroll back to top and start typing while the cursor remains at bottom, it doesn't scroll to there right away as I have just adjusted a 20pt space to content offset. I'm not sure how to calculate the content offset of tableview based on the cursor point. Below is my code so far. Any help is appreciated.
-(void)adjustTextScroll:(UITextView *)textView
{
UITextRange *selectedTextRange = textView.selectedTextRange;
CGRect windowRect = CGRectZero;
if (selectedTextRange != nil)
{
CGRect caretRect = [textView caretRectForPosition:selectedTextRange.end];
windowRect = [textView convertRect:caretRect toView:nil];
}
//Checks if current cursor position is behind keyboard position
if (CGRectGetMinY(windowRect) > (keyboardYpos - 50)) // 50 added for space difference margin from keyboard
{
CGPoint contentOffset = self.tableView.contentOffset;
contentOffset.y += 20 ;
self.tableView.contentOffset = contentOffset;
}
}
//Keyboard notification
- (void)keyboardWasShown:(NSNotification *)notification
{
// Get the size of the keyboard.
CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
CGFloat height = MIN(keyboardSize.height,keyboardSize.width);
CGFloat mainViewHeight = MAX([[UIScreen mainScreen]bounds].size.width,[[UIScreen mainScreen] bounds].size.height);
keyboardYpos = mainViewHeight - height;
}
- (void)textViewDidChange:(UITextView *)textView{
[self adjustTextScroll:textView]
}
Use TPKeyboardAvoiding and let this take care of all scroll issues. I myself have worked on quite a number of apps which uses this. Works like a charm.
I'd like to implement a "zoom" effect on a paging UIScrollView that I've created, but I am having a lot of difficulty. My goal is that as a user begins to scroll to the next page, the current page zooms out to become a little bit smaller. As the next page comes into view, it zooms in until it becomes its full size. The closest thing I could find to an example was this...
https://www.pinterest.com/pin/147141112804210631/
Can anyone give me some pointers on how to accomplish this? I've been banging my head against a wall for the last 3 days on this.
I would recommend using the scrollView.contentOffset.y of your paginated UIScrollView to keep track of the scroll and to use that value to animate the transform of your views inside the UIScrollView.
So add your paginated scrollview and make self as delegate.
paginatedScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, [[self view] bounds].size.height-paginatedScrollViewYOffset)];
[self.view addSubview:paginatedScrollView];
paginatedScrollView.pagingEnabled = YES;
[paginatedScrollView setShowsVerticalScrollIndicator:NO];
[paginatedScrollView setShowsHorizontalScrollIndicator:NO];
[paginatedScrollView setAlwaysBounceHorizontal:NO];
[paginatedScrollView setAlwaysBounceVertical:YES];
paginatedScrollView.backgroundColor = [UIColor clearColor];
paginatedScrollView.contentSize = CGSizeMake([[self view] bounds].size.width, [[self view] bounds].size.height*2); //this must be the appropriate size depending of the number of pages you want to scroll
paginatedScrollView.delegate = self;
Then use the delegate method scrollViewDidScroll to keep track of the scrollView.contentOffset.y
- (void) scrollViewDidScroll:(UIScrollView *)scrollView {
NSLog(#"Scroll Content Offset Y: %f",scrollView.contentOffset.y);
//use here scrollView.contentOffset.y as multiplier with view.transform = CGAffineTransformMakeScale(0,0) or with view.frame to animate the zoom effect
}
Use this Code scrollview its zoom in when scroll next page, the code is given below,
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
GridCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"CollectCell" forIndexPath:indexPath];
cell.myscrollview.minimumZoomScale = 5.0;
cell.myscrollview.zoomScale = 5.0;
cell.myscrollview.contentSize = cell.contentView.bounds.size;
return cell;
}
if you change the zoom scale value its automatically zoom in or zoom out to be showed when scroll next or previous page.
hope its helpful.
I actually just posted an answer to a very similar question, where somebody tried to achieve this effect using a UICollectionView. The link to my answer is here: https://stackoverflow.com/a/36710965/3723434
Relevant piece of code I will post here:
So another approach would be to to set a CGAffineTransformMakeScale( , ) in the UIScrollViewDidScroll where you dynamically update the pages' size based on their distance from the center of the screen.
For every page, calculate the distance of its center to the center of yourScrollView
The center of yourScrollView can be found using this nifty method: CGPoint point = [self.view convertPoint:yourScrollView.center toView:*yourScrollView];
Now set up a rule, that if the page's center is further than x away, the size of the page is for example the 'normal size', call it 1. and the closer it gets to the center, the closer it gets to twice the normal size, 2.
then you can use the following if/else idea:
if (distance > x) {
page.transform = CGAffineTransformMakeScale(1.0f, 1.0f);
} else if (distance <= x) {
float scale = MIN(distance/x) * 2.0f;
page.transform = CGAffineTransformMakeScale(scale, scale);
}
What happens is that the page's size will exactly follow your touch. Let me know if you have any more questions as I'm writing most of this out of the top of my head).
I've done some work on stylized app guide page before.
For Me, I would use CADisplayLink to track the contentOffset.x of the scrollView, associate the value with your animation process. Don't put your views on the scrollView, put them on an overlay view of this scrollView.
This solution follows the philosophy: Fake it before you make it.
Based on CADisplayLink and physics simulation of UIScrollView, you will get smooth animation. Believe me.
What you really want isn't a UIScrollView, it's a UICollectionView with a custom layout. UICollectionViewLayoutAttributes has a transform property that you can set.
Say for example, in layoutAttributesForElementsInRect::
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let attributes = super.layoutAttributesForElementsInRect(rect) else {
return nil
}
return attributes.map { attribute -> UICollectionViewLayoutAttributes in
if attribute.frame.origin.y < 0 {
let scale = -attribute.frame.origin.y / attribute.frame.height
attribute.transform = CGAffineTransformMakeScale(scale, scale)
}
return attribute
}
}
Here, you're filtering by if the element is on the screen (so non-visible elements won't be counted) and checking to see if the y offset is less than 0. If it is, you take the difference between the negated y value and the item's height and turn that into a proportional scale.
You can do it however you want, if you want the scale to be between 1 and 0.5 for example. I like this way of doing things over mucking around with a scroll view.
I have a CustomScrollView which holds a list of UILabels and scrolls through them (the subclassing is for automatic positioning of the views). In the class I have a list of these views stored as an NSMutableArray. I have found that when I ask for label.view.frame.origin after getting the label from the array, I always get {0, 0}. Because of this, the logic I use to scroll does not work (the scroll is done programmatic-ally). I am trying to have the UILabel scroll to the center of the frame of the CustomScrollView. Here is a code sample to show where I am having problems:
#interface CustomScrollView : UIScrollView
#property (nonatomic) NSMutableArray* labels; //This is the array of UILabels
#end
#implementation CustomScrollView
-(void)scrollToIndex:(int)index withAnimation:(bool)animated
{
UILabel *label = (UILabel*)self.labels[index];
CGRect rect = CGRectMake(label.frame.origin.x - ((self.frame.size.width - label.frame.size.width) / 2), 0, self.frame.size.width, self.frame.size.height);
[self scrollRectToVisible:rect animated:animated];
}
#end
TL:DR - label.frame.origin.x is returning me 0 and not what it's relative position is within the superview.
Bonus - Whenever I instantiate my custom scroll view, it automatically adds two subviews which I have no idea where the come from. I set the background color and turn off the scroll bars and scroll enabled.
Thanks in advance for the help.
Edit [Jun 25 11:38] - Turns out the rect I am creating to scroll is correct, but calling [self scrollRectToVisible:rect animated:animated] is just not working.
Edit [Jun 25 12:04] - Here is the method which I call every time I add a subview
-(UILabel*)lastLabel
{
if (self.labels.count == 0)
return nil;
return (UILabel*)self.labels.lastObject;
}
-(void)adjustContentSize
{
if (self.labels.count > 0)
{
float lastModifier = [self lastLabel].frame.origin.x + [self lastLabel].frame.size.width + ((self.frame.size.width - [self lastLabel].frame.size.width) / 2);
self.contentSize = CGSizeMake(MAX(lastModifier, self.contentSize.width), self.frame.size.height);
}
}
Try using the convertRect function:
CGRect positionOfLabelInScrollView = [self.scrollView convertRect:myLabel.frame toView:nil];
[self.scrollView setContentOffset:CGPointMake(0, topOfLabel - positionOfLabelInScrollView.origin.y + positionOfLabelInScrollView.size.height) animated:YES];
This should scroll your scrollView to display the label.
I have a scrollView with multiple textFields, which tracks the active field and makes sure it is visible when the keyboard pops up. It all works well, but when I tab from the 3rd to 4th textField, I get a little up and down "shimmy" before the textField ends up in the right place. Any suggestions?
-(void)keyboardDidShow:(NSNotification *)notification
{
if (keyboardIsShown)return;
NSDictionary* info=[notification userInfo];
// get keyboard size
CGSize keyboardSize=[[info objectForKey:UIKeyboardFrameBeginUserInfoKey]CGRectValue].size;
//Set scrollview insets to make room for keyboard
UIEdgeInsets contentInsets=UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height, 0.0);
scrollView.contentInset=contentInsets;
scrollView.scrollIndicatorInsets=contentInsets;
//scroll the active text field into view
CGRect viewFrame=self.view.frame;
viewFrame.size.height-=keyboardSize.height;
int fieldHeight=self.currentTextField.bounds.size.height;
CGFloat navHeight=self.navigationController.navigationBar.frame.size.height;
CGPoint viewPoint=CGPointMake(0.0, self.currentTextField.frame.origin.y+fieldHeight);
if (!CGRectContainsPoint(viewFrame, viewPoint)) {
//scroll to make sure active field is showing
CGPoint scrollPoint=CGPointMake(0.0, viewPoint.y-keyboardSize.height+navHeight);//+navHeight
[scrollView setContentOffset:scrollPoint animated:YES];
}
}
-(void)showActiveField
{
//this makes sure that activeField shows when selecting another field after initial keyboard show
int fieldHeight=self.currentTextField.bounds.size.height;
CGPoint viewPoint=CGPointMake(0.0, self.currentTextField.frame.origin.y+fieldHeight);
CGRect viewFrame=self.view.frame;
int inset=scrollView.contentInset.bottom;
if (!CGRectContainsPoint(viewFrame, viewPoint)) {
//scroll to make sure active field is showing
CGPoint scrollPoint=CGPointMake(0.0, viewPoint.y-inset);
[scrollView setContentOffset:scrollPoint animated:YES];
}
}
Where do you set keyboardIsShown? Don't you want to do that Right after you check if it is already set?
And then: is the 4th field near the end of the scrollview and you have bounce scroll set?
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;
}
}