-4

I was trying to center the text in the middle of a view, but instead, received an error. Here's my code as a reference.

let textbox = UITextField()
    textbox.text = "Hello"
    textbox.sizeToFit()
    textbox.centerXAnchor.constraint(equalTo: textboxView.centerXAnchor).isActive = true
    textbox.centerYAnchor.constraint(equalTo: textboxView.centerYAnchor).isActive = true
    textbox.delegate = self
    self.textboxView.addSubview(textbox)
Claire Cho
  • 57
  • 1
  • 11

2 Answers2

1

You cannot constraint a view relative to another view unless they are first related.

You need to add the subview first before setting the constraints

let textbox = UITextField()
textbox.text = "Hello"
textbox.translatesAutoresizingMaskIntoConstraints = false
self.textboxView.addSubview(textbox)
textbox.centerXAnchor.constraint(equalTo: textboxView.centerXAnchor).isActive = true
textbox.centerYAnchor.constraint(equalTo: textboxView.centerYAnchor).isActive = true
textbox.delegate = self
Mocha
  • 1,472
  • 7
  • 23
0

You haven’t given lot of detail surrounding the rest of your view controller, so you may have already added it somewhere else.

However, when using autolayout constraints you must turn off auto masking.

textbox.translatesAutoresizingMaskIntoConstraints = false

You should also add the textbox as a subview prior to setting constraints.

Paulo
  • 602
  • 1
  • 7
  • 19