2

I'm new in creating views without interface builder . I'm using NSLayoutAnchors to create views!

when I'm using some view that created in viewcontroller like this :

let borderView:UIView = {

    let view = UIView()
    view.translatesAutoresizingMaskIntoConstraints = false
    view.backgroundColor = UIColor.lightGray
    view.isUserInteractionEnabled = false
    view.alpha = 0.5
    return view

}()

then i use this view to border sth in view like this :

view.addSubview(borderView)
borderView.bottomAnchor.constraint(equalTo: headerView.bottomAnchor).isActive = true
borderView.leftAnchor.constraint(equalTo: headerView.leftAnchor).isActive = true
borderView.rightAnchor.constraint(equalTo: headerView.rightAnchor).isActive = true
borderView.heightAnchor.constraint(equalToConstant: 1).isActive = true

then in another view i try this :

    informationView.addSubview(borderView)

    borderView.topAnchor.constraint(equalTo: informationView.topAnchor).isActive = true
    borderView.leftAnchor.constraint(equalTo: informationView.leftAnchor).isActive = true
    borderView.rightAnchor.constraint(equalTo: informationView.rightAnchor).isActive = true
    borderView.heightAnchor.constraint(equalToConstant: 1).isActive = true

but looks like this view has it's previous constraints end show constraints error !

how can I remove borderView constraints before reusing it ?

2
  • Possible duplicate of Remove all constraints affecting a UIView Commented Apr 12, 2017 at 14:17
  • It's not really a duplicate because the answer is not to reuse the view (removing constraints wouldn't help in this case) Commented Apr 12, 2017 at 14:25

1 Answer 1

7

You can't reuse views. Each view can only be in the view hierarchy one time. You need to make a new bordered view object for each view you want to use it with.

To answer the question, you can remove constraints from a view with view.removeConstraints(view.constraints)

Sign up to request clarification or add additional context in comments.

2 Comments

what is a best practice to make some border view using this method ?
Something like: (1) don't have a property for it (2) make a func that takes a view, makes a new border view, sets constraints and adds it as a sub to the passed in view, so you just do addBorderView(to: view)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.