Skip to content

awakeFromNib is called twice instead of once #7

@smamczak

Description

@smamczak

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions