IOS adding a text view and center it in a parent view

Programmatically adding a UITextView to a parent view, and center the text view inside the parent view. The parent view can be any view container.The text view can be any child view within a parent view.

let parentView = UIView()
let textView = UITextView()
textView.center = parentView.center
textView.textAlignment = NSTextAlignment.center
textView.textColor = UIColor.blue
textView.backgroundColor = UIColor.lightGray
textView.text = "Hello Center View"
textView.isEditable = false
textView.sizeToFit()
parentView.addSubview(textView)

textView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
  textView.widthAnchor.constraint(equalToConstant: 200),
  textView.heightAnchor.constraint(equalToConstant: 30),
  textView.centerXAnchor.constraint(equalTo: parentView.centerXAnchor),
  textView.centerYAnchor.constraint(equalTo: parentView.centerYAnchor)
])

Search within Codexpedia

Custom Search

Search the entire web

Custom Search