Add “padding” to a UITextView

微笑、不失礼 提交于 2019-12-02 17:54:54

EDIT 1/16/2015: This was written in 2012 and is no longer accurate. Use -textContainerInset as mentioned above.

Original post:

Using contentInset won't actually work. You have two reasonable choices: subclass UITextField and override the textRectForBounds: and editingRectForBounds: methods or create your text field transparently over a UIView and style the UIView.

Example of subclassing the UITextField:

- (CGRect)textRectForBounds:(CGRect)bounds {
     return CGRectInset(bounds, 5, 5);
}

- (CGRect)editingRectForBounds:(CGRect)bounds {
     return CGRectInset(bounds, 5, 5);
}

Example of wrapping it in a UIView:

UIView *wrapView = [[UIView alloc] initWithFrame: CGRectMake(10, 10, 200, 30)];
[wrapView addSubview:textView];
wrapView.layer.borderColor = [UIColor darkGrayColor].CGColor;
wrapView.layer.borderWidth = 2.0;
wrapView.layer.cornerRadius = 5.0;

Using iOS7 I have done it just with

[self.textView setTextContainerInset:UIEdgeInsetsMake(0, 12, 0, 12)];

Hope this helps, Mário

Sergej Metelin

This answer is totally wrong. Correct answer is simply:

uitextview.textContainerInset =
       UIEdgeInsetsMake(8,5,8,5); // top, left, bottom, right

(Those values generally match how a UITextField on the same screen looks.)


Use this one:

self.textView.contentInset = UIEdgeInsetsMake(5, 5, 5, 5); 

This worked for me using swift 2.0:

textView.textContainerInset = UIEdgeInsetsMake(10, 10, 10, 10)

For Swift 4.2:

textview.contentInset = UIEdgeInsets(top: 2, left: 10, bottom: 2, right: 10)

For Swift 3 - the answer appears to be similar, but slightly different:

textview.contentEdgeInsets = UIEdgeInsets(top: 2, left: 10, bottom: 2, right: 10)

(Actually, I used the above for a UIButtonView, but as it is so closed to the answers that were posted for UITextView I'm thinking [hoping] that it applies for that too)

This is working in Swift 5:

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

Simply create an extension of UITextView using Container Edge Inset as following:

extension UITextView {
    func leftSpace() {
        self.textContainerInset = UIEdgeInsets(top: 4, left: 6, bottom: 4, right: 4)
    }
}

and use it like:

let textView = UITextView()
textView. leftSpace() 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!