UITextView的contentInset无法正常工作。

4

我正在 UITextView 中显示文本。我需要对文本应用一些填充。当我使用 top 位置的值时它有效果,但是如果我使用其他位置的值就无效。

 txtt_bgImage     = [UIImage imageNamed:@"txtt_bg_ipad.png"];
                  txtt_bgImageView = [[UIImageView alloc] initWithImage:txtt_bgImage];

          txtt=[[UITextView alloc]initWithFrame:CGRectMake(170, 300, 400, 250)];

          txtt.text=productDescription;



                  [txtt  setFont: [UIFont fontWithName:@"verdana" size:15]];

                  txtt.textColor=[UIColor whiteColor];

                  [txtt setBackgroundColor:[UIColor clearColor]];


                  txtt.contentInset = UIEdgeInsetsMake(15,0,0,0);

                //  [txtt  setTextContainerInset:UIEdgeInsetsMake(7, 7, 0, 0)];

                  txtt_bgImageView.frame=CGRectMake(170, 300, 400, 250);


                  [self.view addSubview:txtt_bgImageView];

                  txtt.editable=NO;

          NSLog(@"text is %@",txtt.text);

                   object.object_screentext = txtt;

          [self.view addSubview:txtt];

可能是重复的问题:UITextView contentInset not working in UITextView on iOS 7? - Vincent Guerci
我没有使用iOS7。我已经参考了那个问题,但它没有起作用。 - user3496826
4个回答

6

对于iOS7,请使用textContainerInset

@property(nonatomic, assign) UIEdgeInsets textContainerInset NS_AVAILABLE_IOS(7_0);

对于iOS 7以下版本,请使用contentInset并按以下语法设置UIEdgeInsetsMake

UIKIT_STATIC_INLINE UIEdgeInsets UIEdgeInsetsMake(CGFloat top, CGFloat left, CGFloat bottom, CGFloat right) {
    UIEdgeInsets insets = {top, left, bottom, right};
    return insets;
}

根据您的代码,您仅设置了顶部插入。但是如果您希望设置所有边缘,则必须像下面这样设置内容插入:
if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
       _TxtViewSummary.contentInset = UIEdgeInsetsMake(10, 0, 10, 0);
    } else {
       _TxtViewSummary.textContainerInset = UIEdgeInsetsMake(10, 10, 10, 10);
    }

看起来像这样:

在此输入图片描述


我已经提到这段代码是用于iOS7和Xcode5的。如果你还在使用旧版本,请使用“_TxtViewSummary.contentInset = UIEdgeInsetsMake(10, 0, 10, 0);”。 - Nitin Gohel
我正在使用iOS6.1,为什么contentInset不起作用? - user3496826
在我的端上,检查那个工作代码是否正确连接了IBOutlate或textviewl。 - Nitin Gohel
txtt.contentInset = UIEdgeInsetsMake(15,0,0,0); 这段代码只会在顶部留出空间,而不是左右两侧。请将其替换为 (10, 0, 10, 0)。 - Nitin Gohel
如果我使用负值,比如-20,它会反向工作。为什么正值不起作用呢? - user3496826
显示剩余2条评论

3

textView.textContainerInset = UIEdgeInsets(top: 14, left: 16, bottom: 14, right: 16)

这段代码设置了textView的文本容器边距,上下左右分别为14和16像素。

1
使用此代码:
[txtt  setTextContainerInset:UIEdgeInsetsMake(7, 7, 0, 0)];

此外,正确的元素定位方法是在 layoutSubviews 方法中实现的。

没有可见的@Interface 'UITextView'声明了选择器setTextContainerInset。 - user3496826
这是针对iOS7的。在iOS 7之前的版本中,您需要使用contentInset。 - Vinay Jain

0

另一个可能的解决方案如下:

self.textView.contentInset = UIEdgeInsets(top: 740.0, left: 0, bottom: 20.0, right: 0)
self.textView.contentOffset = CGPoint(x: 0, y: -740)

我遇到了一个不想要的行为,textContentInset 一开始可以正确地放置文本,但是内容会滚动到屏幕外。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接