Skip to content

Instantly share code, notes, and snippets.

@toms972
Last active June 2, 2017 11:18
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save toms972/8330377 to your computer and use it in GitHub Desktop.
Save toms972/8330377 to your computer and use it in GitHub Desktop.
Example of vertical alignment for UITextView content.Implemented as a category over UITextView.The reason to choose a category over subclassing is so that legacy code could be easily tweaked.This hack was inspired by the following blog post: http://www.macbaszii.com/2012/10/ios-dev-uitextview-vertical-alignment.html?q=vertical
//
// UITextView+VerticalAlignment.h
// VerbalShoppingList
//
// Created by Tom Susel on 1/9/14.
//
#import <UIKit/UIKit.h>
@interface UITextView (VerticalAlignment)
- (void)alignToTop;
/**
Client should call this to stop KVO.
*/
- (void)disableAlignment;
@end
//
// UITextView+VerticalAlignment.m
// VerbalShoppingList
//
// Created by Tom Susel on 1/9/14.
//
#import "UITextView+VerticalAlignment.h"
@implementation UITextView (VerticalAlignment)
- (void)alignToTop {
// Get a message whenever the content size changes
[self addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:NULL];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
// When content size change, make sure the content is positioned at the top of the scroll view.
self.contentOffset = CGPointMake(0.0f, 0.0f);
}
- (void)disableAlginment {
[self removeObserver:self forKeyPath:@"contentSize"];
}
@end
@Adelmaer
Copy link

Thanks, it works for me, I've put disableAlignment method in my -(void)viewDidDisappear: method.
Btw there is a typo in the word Alignment in implementation file:

  • (void)disableAlginment ,
    should be - (void)disableAlignment

@Shagans982
Copy link

I second the typo.

@tanvic06
Copy link

tanvic06 commented Jan 4, 2016

Have tried using this code.
I have a doubt on where to use the method disableAlignment, since I have a UITextView as a part of custom UITableViewCell.
I'm using the alignToTop method in cellForRowAtIndexPath while configuring the cell.

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment