Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@Adelmaer Adelmaer commented Nov 25, 2014

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

This comment has been minimized.

Copy link

@Shagans982 Shagans982 commented Dec 3, 2014

I second the typo.

@tanvic06

This comment has been minimized.

Copy link

@tanvic06 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