我在我的iOS应用程序中有一个UITextView,它显示大量的文本。
然后,我通过使用UITextView的offset margin参数来分页此文本。
我的问题是UITextView的填充使我的计算感到困惑,因为它似乎是不同的,取决于我使用的字体大小和字体。
是否有可能移除UITextView内容周围的填充?
我在我的iOS应用程序中有一个UITextView,它显示大量的文本。
然后,我通过使用UITextView的offset margin参数来分页此文本。
我的问题是UITextView的填充使我的计算感到困惑,因为它似乎是不同的,取决于我使用的字体大小和字体。
是否有可能移除UITextView内容周围的填充?
当前回答
在iOS 5上UIEdgeInsetsMake(-8,-8,-8,-8);看起来效果不错。
其他回答
textView滚动也会影响文本的位置,使它看起来不是垂直居中。我通过禁用滚动并将顶部插入设置为0来设法将文本置于视图的中心:
textView.scrollEnabled = NO;
textView.textContainerInset = UIEdgeInsetsMake(0, textView.textContainerInset.left, textView.textContainerInset.bottom, textView.textContainerInset.right);
由于某种原因,我还没有弄清楚,在开始输入之前,光标仍然没有居中,但当我开始输入时,文本立即居中。
这是一个简单的小扩展,将删除苹果的默认边际从每个文本视图在你的应用程序。
注意:界面构建器仍将显示旧的边缘,但你的应用程序将按预期工作。
extension UITextView {
open override func awakeFromNib() {
super.awakeFromNib();
removeMargins();
}
/** Removes the Apple textview margins. */
public func removeMargins() {
self.contentInset = UIEdgeInsetsMake(
0, -textContainer.lineFragmentPadding,
0, -textContainer.lineFragmentPadding);
}
}
在iOS 5上UIEdgeInsetsMake(-8,-8,-8,-8);看起来效果不错。
对于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)
对于 SwiftUI
如果你正在使用UIViewRepresentable制作自己的TextView并想要控制填充,在你的makeUIView函数中,简单地做:
uiTextView。textContainerInset = UIEdgeInsets(上:10,左:18,下:0,右:18)
或者随便你。