将文本垂直和水平居中放在UITextView中

时间:2014-02-25 12:08:37

标签: ios cocoa-touch uitextview

我有一个包含一个单元格的分组表视图。在这个单元格中,我将UITextView放在cellForRowAtIndexPath:中,然后立即创建第一个响应者。

我的问题是:当我开始输入时,文字是左对齐的,不是我想要的水平和垂直居中。这是在iOS 7上。

如何将文本居中?

2 个答案:

答案 0 :(得分:28)

我通过观察UITextView的内容大小来解决这个问题,当contentSize发生任何变化时,更新contentOffset。

按如下方式添加观察者:

[textview addObserver:self forKeyPath:@"contentSize" options:(NSKeyValueObservingOptionNew) context:NULL];

按如下方式处理观察者行动:

-(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};
}

要使textview文本水平居中,请从.xib类中选择textview,然后转到库中并将该对齐设置为中心。

享受。 :)

答案 1 :(得分:1)

非常好的解决方案!这是一个Swift + Interface Builder解决方案,您可以在IB中启用它。

我会把它作为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
        }
    }
}