How to set margins (padding) in UITextView?

Viewed 53150

I have a UITextView for text editing. By default, it has a small margin around the text. I want to increase that margin by a few pixels.

The contentInset property gives me margins, but it does not change the text "wrap width". The text is wrapped at the same width, and the extra "margin" just causes the view to scroll horizontally.

Is there a way to make a UITextView of a certain width display the text with a narrower "wrap width"?

9 Answers

if you want to set padding from one side, you can use below code:

 textView.contentInset.left = 5 //For left padding
 textView.contentInset.right = 5 //For right padding
 textView.contentInset.top = 5 //For top padding
 textView.contentInset.bottom = 5 //For bottom padding

Swift + iOS 12: A different approach

Setting padding to the left + right side of our UITextView did let the text disappear when entered more that 9 lines of text. Using the solution of @rajesh helped to solve this issue:

Make sure to invoke the method whenever text did change + the device rotates.

    /// Updates the left + right padding of the current text view.
    /// -> leftRightPadding value = 11.0
    func updateLeftRightPadding() {
        let leftPadding = UIBezierPath(rect: .init(x: 0.0, y: 0.0,
                                       width: leftRightPadding, height: contentSize.height))
        let rightPadding = UIBezierPath(rect: .init(x: frame.width - leftRightPadding, y: 0.0,
                                        width: 11, height: contentSize.height))
        textContainer.exclusionPaths = [leftPadding, rightPadding]
    }
Related