ios 将 UITextView 中的文本垂直和水平居中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22013768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Center the text in a UITextView, vertically and horizontally
提问by user3083408
I have a grouped table view with one cell. In this cell I'm putting a UITextView
in cellForRowAtIndexPath:
, and I instantly make this first Responder.
我有一个带有一个单元格的分组表视图。在这个小区,我把一个UITextView
在cellForRowAtIndexPath:
,我立即让这个第一个响应。
My problem is: When I start typing, the text is left-justified, not centered horizontally and vertically as I want. This is on iOS 7.
我的问题是:当我开始打字时,文本是左对齐的,而不是我想要的水平和垂直居中。这是在 iOS 7 上。
How can I center the text?
如何将文本居中?
回答by Vinay Jain
I resolve this issue by observing the contentsize of UITextView, when there is any change in the contentSize, update the contentOffset.
我通过观察 UITextView 的 contentsize 来解决这个问题,当 contentSize 有任何变化时,更新 contentOffset。
Add observer as follows:
添加观察者如下:
[textview addObserver:self forKeyPath:@"contentSize" options:(NSKeyValueObservingOptionNew) context:NULL];
Handle the observer action as follows:
处理观察者动作如下:
-(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};
}
To make the textview text horizontally center, select the textview from .xib class and go to the library and in that set Alignment as center.
要使 textview 文本水平居中,请从 .xib 类中选择 textview 并转到库,然后将对齐设置为居中。
Enjoy. :)
享受。:)
回答by superarts.org
Very good solution! This is a Swift
+ Interface Builder
solution so that you can enable it in IB.
很好的解决方案!这是一个Swift
+Interface Builder
解决方案,因此您可以在 IB 中启用它。
I'll put it as part of the LSwift
library.
我会把它作为LSwift
图书馆的一部分。
extension UITextView {
@IBInspectable var align_middle_vertical: Bool {
get {
return false // TODO
}
set (f) {
self.addObserver(self, forKeyPath:"contentSize", options:.New, context:nil)
}
}
override public func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject:AnyObject], context: UnsafeMutablePointer<Void>) {
if let textView = object as? UITextView {
var y: CGFloat = (textView.bounds.size.height - textView.contentSize.height * textView.zoomScale)/2.0;
if y < 0 {
y = 0
}
textView.content_y = -y
}
}
}
public extension UIScrollView {
public var content_x: CGFloat {
set(f) {
contentOffset.x = f
}
get {
return contentOffset.x
}
}
public var content_y: CGFloat {
set(f) {
contentOffset.y = f
}
get {
return contentOffset.y
}
}
}