IOS-从 UITextView 删除所有填充

在 SO 中有许多很好的例子可以去除 UITextView 的左边填充。

如何在 UITextView 中丢失页边距/填充?

然而,我需要删除正确的填充也。

我试过了。

[tv setContentInset: UIEdgeInsetsMake(-4,-8,-8,-X)];//where X is any integer

以及最后两个值的每个其他排列都去除了填充,但似乎没有任何效果。也试过了

[tv sizeToFit];
[tv setTextAlignment:[NSTextAlignmentRight]];

文本视图中的下列文本显示“00”

enter image description here

43790 次浏览

Please try sub-classing the UITextView and overriding the following method:

    - (id)styleString
{
return [[super styleString] stringByAppendingString:@"; line-height: 1.6em;margin-right: 30px; margin-left: 0px; margin-top: 0px;"];
}

Apparently; you can tweak the margin-left, margin-top & whatever you want ;)

Although it is iOS 7 only, an extremely clean solution is to set the textView's textContainerInsets as such:

[textView setTextContainerInset:UIEdgeInsetsZero];
textView.textContainer.lineFragmentPadding = 0; // to remove left padding

This will effectively remove all padding (insets) around the text inside the text view. If your deployment target is iOS 7+ then this is the best solution thus far.

My problem is solved this way

if([Utils isiOS7orHigher]){
commentView.textContainerInset = UIEdgeInsetsZero;
}else {
commentView.contentInset = UIEdgeInsetsMake(-11,-8,0,0);
}

for more see http://foobarpig.com/iphone/get-rid-of-uitextview-padding.html

To completely remove all padding, the lineFragmentPadding must be taken into account.

let padding = textView.textContainer.lineFragmentPadding
textView.textContainerInset =  UIEdgeInsets(top: 0, left: -padding, bottom: 0, right: -padding)

The lineFragmentPadding default value is 5, and is at the beginning and end of fragment rectangle.

Some answers suggested setting lineFragmentPadding to 0. However, as per discussed in the doc, it is not designed to express text margins. So do not set it to 0.

Swift 4 version for the OA

self.tDescription.textContainerInset = UIEdgeInsets.zero
self.tDescription.textContainer.lineFragmentPadding = 0

For iOS 11.7

Following code worked for me:

    textView.textContainer.lineFragmentPadding = CGFloat(0.0)
textView.textContainerInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
textView.contentInset = UIEdgeInsets(top: 0,left: 0,bottom: 0,right: 0)

From the Official Documentation:

: It is possible to set the text container and view sizes and resizing behavior so that the inset cannot be maintained exactly, although the text system tries to maintain the inset wherever possible.

In any case, the textContainerOrigin and size of the text container are authoritative as to the location of the text container within the view. The text itself can have an additional inset, inside the text container, specified by the lineFragmentPadding method of NSTextContainer.