Search code examples
swiftuitextfielddelegate

Thread 1: signal SIGABRT swift


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)

Solution

  • 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