您的位置:首页 > 产品设计 > UI/UE

让UITextView文字垂直居中

2015-09-03 17:20 246 查看
让UITextView和UITextField同样拥有垂直居中的属性,建议单独一个类继承自UITextView

只需要初始化UITextView之后用KVO监听 "contentSize" 属性即可

_textView = [[XHMessageTextView
alloc]
init];

_textView.delegate =
self;

_textView.placeHolder =
@"我来评论...";

// _textVie.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;

//byliuchao

_textView.frame =
CGRectMake(10,
2, KWIDTH -
70, 38);

_textView.font = [UIFont
systemFontOfSize:14];

_textView.textColor =
FONTCOLOR;

_textView.placeHolderTextColor = [UIColor
colorWithRed:189/255.0
green:193/255.0
blue:199/255.0
alpha:0.5];

_textView.layer.borderColor = [UIColor
colorWithRed:189/255.0
green:193/255.0
blue:199/255.0
alpha:0.5].CGColor;

_textView.layer.cornerRadius =
5.0;

//end

[_textView
addObserver:self
forKeyPath:@"contentSize"options:NSKeyValueObservingOptionNew
context:nil];

_textView.layer.borderWidth =
0.5;

_textView.layer.masksToBounds =
YES;

_textView.returnKeyType =
UIReturnKeyDone;
[dockview
addSubview:_textView];

#pragma mark - KVO

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary
*)change context:(void *)context
{

CGFloat topCorrect = ([_textView
bounds].size.height - [_textView
contentSize].height);
topCorrect = (topCorrect <0.0 ?
0.0 : topCorrect);

_textView.contentOffset = (CGPoint){.x =
0, .y = -topCorrect /
2};
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: