user1591668
user1591668

Reputation: 2893

IOS Swift confusing error on using nib file for reusable Views

I am trying to do a simple reusable view and for some reason I am getting a un-specific error . I am following this tutorial https://www.youtube.com/watch?v=H-55qZYc9qI . As stated this is my first time trying this . Everything compiles correctly but when I go to that View I get a runtime error . What is weird is that I followed that tutorial exactly and am getting the error. The names are correct and the view is connected properly . Any suggestions

import UIKit

class streamShared: UIView {
    @IBOutlet var view: streamShared!

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        UINib(nibName: "streamShared", bundle: nil).instantiate(withOwner: self, options: nil)
      addSubview(view)
}
}

enter image description here

enter image description here

Upvotes: 0

Views: 120

Answers (1)

Nicolas Miari
Nicolas Miari

Reputation: 16256

You've got yourself an infinite recursion: streamShared.init(coder:) is calling itself.

I think the subview should be of type UIView:

import UIKit

// PLEASE name your classes, structs and enums Capitalized!
class StreamShared: UIView {

    var view: UIView!

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        self.view = UINib(nibName: "streamShared", bundle: nil).instantiate(withOwner: self, options: nil)
        addSubview(view)
    }
}

Also, change the class of the main view in your xib file to the default UIView (grayed); otherwise, when reading the xib and instantiating the views contained therein, StreamShared.init(coder:) will still be called.

Upvotes: 1

Related Questions