How to Add a Border to a Text View (Swift)

In this article, we will explain how to add a border to a Text View in an iOS app using Swift.

When you want to allow multiple lines of text input, you should use UITextView instead of UITextField.

However, by default, UITextView does not have a border.


For example, in the storyboard of your iOS app, add a Text View and a button like this:

How to Add Border to Text View in Swift 1


When you run this in the simulator, it will look like this:

How to Add Border to Text View in Swift 2


In most cases, you might want a border, so let's add one.

Open ViewController.swift in Assistant Editor, and create an outlet for the UITextView named noteTextView.

How to Add Border to Text View in Swift 3

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var noteTextView: UITextView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

Then, add the following code inside viewDidLoad() in ViewController.swift:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var noteTextView: UITextView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        noteTextView.layer.borderColor = UIColor.lightGray.cgColor
        noteTextView.layer.borderWidth = 0.5
        noteTextView.layer.cornerRadius = 5
        noteTextView.contentInset = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
    }
}

How to Add Border to Text View in Swift 4

Line 10 sets the border color of the Text View to light gray.

Line 11 sets the border width of the Text View to 0.5.

Line 12 sets the cornerRadius of the Text View to 5, making the corners slightly rounded.

Line 13 uses UIEdgeInsets to add padding, so the text inside does not touch the edges directly.


When you run this in the simulator, it will look like this:

How to Add Border to Text View in Swift 5

You can now see a light gray border around the Text View.


When you type text, it will look like this:

How to Add Border to Text View in Swift 6

You can adjust the border color, width, and other styles according to your preference.


That's it! We have explained how to add a border to a Text View in a Swift iOS app.