我在我的iOS应用程序中有一个UITextView,它显示大量的文本。

然后,我通过使用UITextView的offset margin参数来分页此文本。

我的问题是UITextView的填充使我的计算感到困惑,因为它似乎是不同的,取决于我使用的字体大小和字体。

是否有可能移除UITextView内容周围的填充?


当前回答

对于Swift 4, Xcode 9

使用下面的函数。它可以改变UITextView中文本的边距/填充:

public func UIEdgeInsetsMake(_ top: CGFloat, _ left: CGFloat, _ bottom: CGFloat, _ right: CGFloat) -> UIEdgeInsets

所以在这种情况下,它是:

 self.textView?.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0)

其他回答

使用用户定义运行时属性的故事板或接口构建器解决方案:

iOS 7.1和iOS 6.1的截图内容为contentInset ={{-10, -5},{0,0}}。

[firstNameTextField setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];

你需要在didMoveToSuperView上设置inset和lineFragmentPadding

@IBDesignable class UITextViewFixed: UITextView {
    override func didMoveToSuperview() {
        super.didMoveToSuperview()
        setup()
    }
    func setup() {
        textContainerInset = UIEdgeInsets.zero
        textContainer.lineFragmentPadding = 0
    }
}

textView滚动也会影响文本的位置,使它看起来不是垂直居中。我通过禁用滚动并将顶部插入设置为0来设法将文本置于视图的中心:

    textView.scrollEnabled = NO;
    textView.textContainerInset = UIEdgeInsetsMake(0, textView.textContainerInset.left, textView.textContainerInset.bottom, textView.textContainerInset.right);

由于某种原因,我还没有弄清楚,在开始输入之前,光标仍然没有居中,但当我开始输入时,文本立即居中。

在iOS 5上UIEdgeInsetsMake(-8,-8,-8,-8);看起来效果不错。