2 回答
TA贡献1789条经验 获得超8个赞
只需要初始化UITextView之后用KVO监听 "contentSize" 属性即可
_textView = [[UITextView alloc] initWithFrame:CGRectMake(20.0f, DOT_COORDINATE, 260.0f,TABLE_VIEW_ROW_HEIGHT*2)];
_textView.delegate = self;
_textView.text = PROMPT_TEXT;
_textView.font = [UIFont systemFontOfSize:18.0f];
_textView.textColor = [UIColor lightGrayColor];
[self.contentView addSubview:_textView];
[_textView addObserver:self forKeyPath:@"contentSize" options:(NSKeyValueObservingOptionNew) context:NULL];
#pragma mark - KVO
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void *)context
{
UITextView *tv = object;
// Center vertical alignment
CGFloat topCorrect = ([tv bounds].size.height - [tv contentSize].height * [tv zoomScale])/2.0;
topCorrect = ( topCorrect < 0.0 ? 0.0 : topCorrect );
tv.contentOffset = (CGPoint){.x = 0, .y = -topCorrect};
// // Bottom vertical alignment
// CGFloat topCorrect = ([tv bounds].size.height - [tv contentSize].height);
// topCorrect = (topCorrect <0.0 ? 0.0 : topCorrect);
// tv.contentOffset = (CGPoint){.x = 0, .y = -topCorrect};
}
TA贡献1798条经验 获得超7个赞
代码如下:
//注册 监听text属性的事件
[myTextView addObserver:selfforKeyPath:@"contentSize"options:NSKeyValueObservingOptionNewcontext:nil];//也可以监听contentSize属性
//接收处理
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
UITextView *mTrasView = object;
CGFloat topCorrect = ([mTextbounds].size.height - [mTextcontentSize].height);
topCorrect = (topCorrect <0.0 ?0.0 : topCorrect);
mText.contentOffset = (CGPoint){.x =0, .y = -topCorrect/2};
}
当然,别忘了先设置一下水平居中属性。
//
//如何做到输入时动态改变:也许可以在
- (void)textViewDidChange:(UITextView *)textView;进行上述的偏移处理,同时可以加上动画效果,以便达到UITextFiled,居中输入的动态效果,此处只提供一个思路,其方法进行过验证,可行。但细节上需要你自己根据情况改变。
添加回答
举报