use*_*408 16 cocoa-touch uitextview ios
我有一个带有一个单元格的分组表视图.在这个小区,我把一个UITextView在cellForRowAtIndexPath:,我立即让这个第一个响应.
我的问题是:当我开始输入时,文本是左对齐的,不是我想要的水平和垂直居中.这是在iOS 7上.
我该如何将文本居中?
Vin*_*ain 28
我通过观察UITextView的内容大小来解决这个问题,当contentSize有任何变化时,更新contentOffset.
添加观察者如下:
[textview addObserver:self forKeyPath:@"contentSize" options:(NSKeyValueObservingOptionNew) context:NULL];
Run Code Online (Sandbox Code Playgroud)
处理观察者动作如下:
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
UITextView *txtview = object;
CGFloat topoffset = ([txtview bounds].size.height - [txtview contentSize].height * [txtview zoomScale])/2.0;
topoffset = ( topoffset < 0.0 ? 0.0 : topoffset );
txtview.contentOffset = (CGPoint){.x = 0, .y = -topoffset};
}
Run Code Online (Sandbox Code Playgroud)
要使textview文本水平居中,请从.xib类中选择textview,然后转到库中并将该对齐设置为中心.
请享用.:)