Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

awakeFromNib is called twice instead of once #7

Open
smamczak opened this issue May 27, 2020 · 0 comments
Open

awakeFromNib is called twice instead of once #7

smamczak opened this issue May 27, 2020 · 0 comments

Comments

@smamczak
Copy link
Contributor

Hi, as I understand the purpose of awakeFromNib() is that is should me called once after awaking from nib. The downside of using awakeAfter(using: aDecoder) is that the method is called twice: first time where view is awaken from e.g. UIViewController and second time when our view is awaken from the .xib

I have managed to find a workaround by checking if superview == nil. It equals nil when awaking from UIVIewController and superview is not set yet. When awake from .xib is called due awakeAfter(using:) then the superview is not nil

@IBDesignable
open class MyNibView: UIView, NibLoadable {

    open class var nibName: String {
        return String(describing: self)
    }

    open override func awakeAfter(using aDecoder: NSCoder) -> Any? {
        return nibLoader.awakeAfter(using: aDecoder, super.awakeAfter(using: aDecoder))
    }

    open override func awakeFromNib() {
        // this will fire twice
        guard self.superview == nil else { return }
        self.awakeFromNibOnce()
    }

    open func awakeFromNibOnce() {
        // this will fire once
    }
}

My question is: can we manage to do it without the workaround?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant