当我的 UiTextView
添加 2 行或更多行时,它看起来不错,但当用户只输入一行时,文本停留在 UiTextView
的中间。我怎样才能强制它留在 UiTextView
的左上角?
最佳答案
您可以查看此博客 ( iOS: Vertical aligning text in a UITextView ),其中解释了如何进行居中和底部垂直对齐。使用类似的逻辑并在您的案例中将 contentOffset y 参数设置为零以使其顶部对齐。
这是博客中的代码,
- (void) viewDidLoad {
[textField addObserver:self forKeyPath:@"contentSize" options:(NSKeyValueObservingOptionNew) context:NULL];
[super viewDidLoad];
}
-(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};
}
关于ios - UiTextView - 仅添加一行时的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14408668/