Skip to content

Instantly share code, notes, and snippets.

@jenshandersson
Last active December 29, 2015 01:30
Show Gist options
  • Save jenshandersson/9198076 to your computer and use it in GitHub Desktop.
Save jenshandersson/9198076 to your computer and use it in GitHub Desktop.
Simple UITextView subclass for vertically aligning text in middle.
//
// JHAVerticalTextView.h
// Quotes background
//
// Created by Jens Andersson on 23/02/14.
// Copyright (c) 2014 Jens Andersson. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface JHAVerticalTextView : UITextView
@end
//
// JHAVerticalTextView.m
// Quotes background
//
// Created by Jens Andersson on 23/02/14.
// Copyright (c) 2014 Jens Andersson. All rights reserved.
//
#import "JHAVerticalTextView.h"
@implementation JHAVerticalTextView
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self setupObserver];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
[self setupObserver];
[self alignVertically];
}
return self;
}
- (void)setupObserver {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(alignVertically)
name:UITextViewTextDidChangeNotification
object:self];
}
- (void)setText:(NSString *)text {
[super setText:text];
[self alignVertically];
}
- (void)alignVertically
{
CGSize size = [self sizeThatFits:self.frame.size];
CGFloat offsetY = (CGRectGetHeight(self.frame) - size.height) / 2;
self.contentInset = UIEdgeInsetsMake(offsetY, 0, 0, 0);
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
@skywalkerlw
Copy link

Thanks so much.
I tried to replace the text size calculation with self.contentSize. It works in iOS8, but fails in iOS9. What's the problem of using "contentSize"?

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