Last active
December 29, 2015 01:30
-
-
Save jensellfors/9198076 to your computer and use it in GitHub Desktop.
Simple UITextView subclass for vertically aligning text in middle.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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"?