user1028028
user1028028

Reputation: 6433

Swift change class at runtime

So I have 3 views set up in interface builder (XCode 6). They are linked to the ViewController that owns them. Also I have 3 subclasses of UIVIew in my project. At runtime I would need to change the class of one of the views from UIView to my custom view subclass.

How do I do this in swift? (I need all the autolayout set up in IB to work the same after the change).

Upvotes: 1

Views: 2334

Answers (1)

Keenle
Keenle

Reputation: 12200

To achieve what you need you can create a view in IB and later in the code add required view as a subview.

To make added view occupy all container view space you need either update child view's frame or setup auto-layout constraints. Variant with frames needs to be repeated each time container view changes it size. Code bellow:

Auto-Layout Contraints

override func viewDidLoad() {
    super.viewDidLoad()

    self.myView = UIView(frame: CGRect())
    self.myView.setTranslatesAutoresizingMaskIntoConstraints(false)
    self.myViewContainer.addSubview(self.myView)

    self.myViewContainer.addConstraint(NSLayoutConstraint(item: self.myView, attribute: .Top, relatedBy: .Equal, toItem: self.myViewContainer, attribute: .Top, multiplier: 1.0, constant: 0))
    self.myViewContainer.addConstraint(NSLayoutConstraint(item: self.myView, attribute: .Right, relatedBy: .Equal, toItem: self.myViewContainer, attribute: .Right, multiplier: 1.0, constant: 0))
    self.myViewContainer.addConstraint(NSLayoutConstraint(item: self.myView, attribute: .Bottom, relatedBy: .Equal, toItem: self.myViewContainer, attribute: .Bottom, multiplier: 1.0, constant: 0))
    self.myViewContainer.addConstraint(NSLayoutConstraint(item: self.myView, attribute: .Left, relatedBy: .Equal, toItem: self.myViewContainer, attribute: .Left, multiplier: 1.0, constant: 0))
}

Manual Frame Updates

@IBOutlet var myViewContainer: UIView
var myView: UIView!

override func viewDidLoad() {
    super.viewDidLoad()

    self.myView = UIView(frame: CGRect())
    self.myViewContainer.addSubview(self.myView)
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    self.myView.frame = self.myViewContainer.bounds
}

Frame updates can be done even if container view has auto-layout constraints.

Upvotes: 2

Related Questions