create a textview inside scrollview in swift

To create a UITextView inside UIScrollView using Auto Layout in Swift, follow the steps below:

  1. Create a UIScrollView and add it to the view hierarchy.
main.swift
let scrollView = UIScrollView()
view.addSubview(scrollView)
60 chars
3 lines
  1. Enable Auto Layout for the UIScrollView and set its constraints to fill the view.
main.swift
scrollView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
    scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
    scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
    scrollView.topAnchor.constraint(equalTo: view.topAnchor),
    scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
365 chars
8 lines
  1. Create a UITextView and add it to the UIScrollView.
main.swift
let textView = UITextView()
scrollView.addSubview(textView)
60 chars
3 lines
  1. Enable Auto Layout for the UITextView and set its constraints:
  • Leading, Trailing, Top and Bottom to the UIScrollView equals to 0.
  • Width to the width of the view minus the horizontal margin (optional).
main.swift
textView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
    textView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
    textView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
    textView.topAnchor.constraint(equalTo: scrollView.topAnchor),
    textView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
    textView.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -16)
])
458 chars
9 lines

Now you have a UITextView inside UIScrollView with Auto Layout.

gistlibby LogSnag