如何在iOS中为UITextView设置内容插入

39

我有一个UITextView,并设置了内容插图:

[atextView setContentInset:UIEdgeInsetsMake(0, 10, 0, 0)];

这段代码在iOS 6.1及以下版本中有效,但在iOS 7.0中没有效果。


3
有没有一种在Storyboard中完成这个操作的方式?! - Fattie
你尝试过更新的答案吗? - Muruganandham K
是的,有的,请查看我下面的解决方案,Joe Blow。 - Bence Pattogato
@BencePattogato 谢谢你的更新。 - Muruganandham K
2个回答

140

得到答案:

[atextView  setTextContainerInset:UIEdgeInsetsMake(7, 7, 0, 0)];

问题已经得到解决。

而在Swift中...

@IBOutlet var tv:UITextView!
override func awakeFromNib() {
    super.awakeFromNib()
    tv.textContainerInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}

更新:有另外一种方法可以做到。

UIView *spacerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
[msgtext setLeftViewMode:UITextFieldViewModeAlways];
[msgtext setLeftView:spacerView];

嘿@murugha23,我需要你的帮助,关于你如何解决IOS7中textview setContentInset问题。 - Anand
4
请使用setTextContainerInset代替setContentInset。如果您想提供iOS的先前版本,则请检查当前设备系统版本的条件。 - Muruganandham K
如果您能为我提供一个包括键盘和文本视图各种方法的类的示例代码,那将非常好,这样我就可以清楚地了解它。 - Anand
其实你的问题是什么?它是设置不当还是根本没有设置? - Muruganandham K
请注意,您只应该使用其中一个。同时使用两者会导致不良的加性行为。 - Oran Dennison
显示剩余3条评论

1

一种替代而且可能更加方便的方法是,通过子类化UITextField并添加@IBInspectable插入属性。

import UIKit

class UITextfieldWithInset: UITextField {

    @IBInspectable
    var textfieldInset: CGPoint = CGPointMake(0, 0)

    override func textRectForBounds(bounds: CGRect) -> CGRect {
        return CGRectInset(bounds, textfieldInset.x, textfieldInset.y)
    }

    override func editingRectForBounds(bounds: CGRect) -> CGRect {
        return CGRectInset(bounds, textfieldInset.x, textfieldInset.y)
    }

    override func placeholderRectForBounds(bounds: CGRect) -> CGRect {
        return CGRectInset(bounds, textfieldInset.x, textfieldInset.y)
    }

}

5
这是一个适用于 UITextField 的不错答案,但问题是关于 UITextView 的。 - dulgan

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