0%

iOS UITextView 内容上下居中

在UITextView中,如果想要实现左右居中,可以通过设置textAligment属性来设置,但如果要实现上下居中呢?

初始化

1
2
3
4
5
6
7
8
9
-(instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self config];
[self setText:@"\n"];
[self setText:@""];
}
return self;
}

添加contentSize监听

1
2
3
4
5
6
7
- (void)config {
self.delegate = self;
self.font = [UIFont systemFontOfSize:32];
[self hasUpdateContentInset];
[self addObserver:self forKeyPath:kContentSize options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
[self updateContentInset];
}

keyvalue observe

1
2
3
4
5
6
7
8
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSLog(@"change :%@",change);
if ([keyPath isEqualToString:kContentSize])
{
[self updateContentInset];
}
}

设置垂直方向contentInset

1
2
3
4
5
6
7
8
- (void)updateContentInset {
NSLog(@"contentSize %@",NSStringFromCGSize(self.contentSize));
CGFloat deadSpace = (CGRectGetHeight(self.bounds) - self.contentSize.height);
CGFloat inset = MAX(0, deadSpace/2.0);
self.contentInset = UIEdgeInsetsMake(inset, self.contentInset.left, inset, self.contentInset.right);
self.contentOffset = CGPointMake(0, -inset);
[self layoutSubviews];
}