[textView 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 = ([mTrasView bounds].size.height - [mTrasView contentSize].height);
topCorrect = (topCorrect <0.0 ?0.0 : topCorrect);
mTrasView.contentOffset = (CGPoint){.x =0, .y = -topCorrect/2};
textView.font = [UIFont systemFontOfSize:17];
textView.textColor = [UIColor whiteColor];
CGSize singleSize = [@"你好" sizeWithFont:[UIFontsystemFontOfSize:17]constrainedToSize:CGSizeMake(textView.frame.size.width,MAXFLOAT)];
CGSize textSize = [mTrasView.text sizeWithFont:[UIFontsystemFontOfSize:17]constrainedToSize:CGSizeMake(textView.frame.size.width,MAXFLOAT)];
NSInteger lines = textSize.height / singleSize.height;
if (lines > 1) {
textView.textAlignment = NSTextAlignmentLeft;
}else {
textView.textAlignment = NSTextAlignmentCenter;
}
}
本文介绍了如何在Swift中监听并处理UI元素的大小变化,具体实现为在TextView上添加观察者来监听其内容大小的变化,并据此进行滚动位置和字体颜色的调整。通过计算TextView顶部的修正值和设置滚动偏移量,实现文本内容的完美布局,同时根据文本行数调整文本对齐方式,确保阅读体验的流畅性和视觉美观。
3248

被折叠的 条评论
为什么被折叠?



