By pkluz


2011-12-11 00:25:31 8 Comments

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.

5 comments

@ChikabuZ 2017-05-27 16:59:36

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
}

enter image description here

Another way is to create view programmatically and return as inputAccessoryView.

@Andres Canella 2016-04-15 18:11:06

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

enter image description here

(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)
}

@rcpfuchs 2016-04-22 05:24:51

works great, tested on ios 8.3.1 device!

@Andres Canella 2016-04-22 06:00:28

Thanks! Added to description.

@rcpfuchs 2016-04-22 06:15:54

Great, I also added a pull request :-) I heard you like contributions.

@Andres Canella 2016-04-22 06:29:22

Excellent!! I'll Check it out tomorrow.

@alexgophermix 2013-11-15 23:01:57

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.

MessageComposerView

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!

@Raspu 2014-04-10 02:01:11

Nice solution, well commented, and functional! Could you please set it as a Cocoapod?

@alexgophermix 2014-04-10 08:16:47

That's a great suggestion! I'll try to set that up as soon as possible - hopefully in the next few weeks.

@alexgophermix 2014-05-04 21:51:08

Hi Raspu, sorry for the delay. I've set the project up as a Cocoapod. I haven't yet added it to the CocoaPods specs. Please let me know if there are any problems.

@Raspu 2014-05-07 01:39:07

Thanks, I will try it today!

@Evan Layman 2014-07-02 05:59:07

This should really be the accepted answer!

@alexgophermix 2014-07-02 16:21:59

Thanks for the kind words Evan :)

@David 2015-02-03 07:26:43

Is this still available via Cocoapods?

@alexgophermix 2015-02-03 17:52:14

You can directly install the pod via the github URL. I haven't submitted it to the cocoapods repo though. I'm currently working on a fix to get the lib working on iOS 8

@Bista 2015-04-17 12:38:41

support for iOS8 added?

@alexgophermix 2015-04-17 16:50:18

Yup I'm currently using it in an iOS 7&8 project of mine

@Fede Henze 2015-09-07 14:08:38

Anyone can provide a sample code?

@alexgophermix 2015-09-08 18:08:17

@FedeHenze in the initialization of your UIViewController to which you want to add a message composer, adding the above mentioned 3 lines of code should be all you need. Are you running into problems with the lib?

@Fede Henze 2015-09-08 19:46:03

I solved the problem, thanks!

@smnh 2013-10-06 10:10:37

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;
    }
}

@Frade 2014-02-24 17:35:43

is your phone drunk or it's me??

@Raspu 2014-04-10 02:18:17

go home @Frade, you are drunk

@pkluz 2011-12-12 05:22:40

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:

  1. 'MessageInputView' is a UIView containing my 'GrowingUITextView' (it also contains a "Send" Button and the background image).
  2. 'ChatView' is the view that belongs to the ChatViewController that displays all the Chatbubbles and has my 'MessageInputView' docked at the bottom.
  3. '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.

@Alex1987 2012-01-20 11:47:04

Hi man, did you post your code to github?

@ma11hew28 2013-10-23 03:28:19

An easier way would be to set keyboardAccessoryView.backgroundColor = [UIColor clearColor] and keyboardAccessoryView.userInteractionEnabled = NO. Then if possible, constrain keyboardAccessoryView's height to that of MessageInputView. Leave MessageInputView as a subview of ChatView and just constrain its top to that of keyboardAccessoryView. Auto Layout: Create constraint between two views in separate windows

@ma11hew28 2014-06-23 05:34:38

Never mind. I think I found a simpler solution: stackoverflow.com/a/24358901/242933

@Gil Sand 2015-01-08 17:21:05

Any news @wasabii ?

Related Questions

Sponsored Content

92 Answered Questions

37 Answered Questions

[SOLVED] Close iOS Keyboard by touching anywhere using Swift

  • 2014-06-09 18:38:10
  • lagoon
  • 321117 View
  • 365 Score
  • 37 Answer
  • Tags:   ios swift uikeyboard

34 Answered Questions

[SOLVED] How to change the name of an iOS app?

  • 2008-10-27 03:07:03
  • Robert Gould
  • 447877 View
  • 957 Score
  • 34 Answer
  • Tags:   ios

0 Answered Questions

0 Answered Questions

5 Answered Questions

[SOLVED] InputAccessoryView docked at bottom

1 Answered Questions

iOS Keyboard is tiny after rotation to landscape

1 Answered Questions

[SOLVED] Has anyone found a good way of using the new iOS5 keyboard events?

Sponsored Content