0

I want to create a nib and attach it to my viewcontroller. To create the nib, this is what I've done...

First I added a blank view and designed the view as desired. Then I added a swift file and added this code in it...

class VerificationCodeView: UIView {
    @IBOutlet var contentView: UIView!
    @IBOutlet weak var mainLabel: UILabel!
    fileprivate weak var view: UIView!

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    private func commonInit() {
        Bundle.main.loadNibNamed("VerificationCodeView", owner: self, options: nil) //CRASHES HERE
        addSubview(contentView)
        contentView.frame = self.bounds
        contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
    }
}

Then in the viewcontroller, in the storyboard, I added a blank view and made it a class of VerificationCodeView.

In the viewDidLoad of the viewcontroller, this is what I did to call the VerificationCodeView...

@IBOutlet weak var verificationCodeView1: VerificationCodeView! //OUTLET
fileprivate var loadingView: VerificationCodeView?

and in the viewDidLoad,

loadingView = VerificationCodeView(frame: verificationCodeView1.frame)

But when the breakpoint reaches the line Bundle.main.loadNibNamed("VerificationCodeView", owner: self, options: nil) in the class VerificationCodeView, it crashes.

What is it that I'm doing wrong here...?

EDIT 1:

This is the entire error log displayed...

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle <…….> (loaded)' with name 'VerificationCodeView''
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000109a261bb __exceptionPreprocess + 331
    1   libobjc.A.dylib                     0x0000000108fc4735 objc_exception_throw + 48
    2   CoreFoundation                      0x0000000109a26015 +[NSException raise:format:] + 197
    3   UIKitCore                           0x0000000112502d94 -[UINib instantiateWithOwner:options:] + 497
    4   UIKitCore                           0x0000000112503d17 -[NSBundle(UINSBundleAdditions) loadNibNamed:owner:options:] + 214
    5   MyApp            0x0000000106e01a1d $S24MyApp20VerificationCodeViewC10commonInit33_9E22480CE8C5AA6EA6A32BC6307198A8LLyyF + 205
    6   MyApp            0x0000000106e0159f $S24MyApp20VerificationCodeViewC5coderACSgSo7NSCoderC_tcfc + 431
    7   MyApp            0x0000000106e0162f $S24MyApp20VerificationCodeViewC5coderACSgSo7NSCoderC_tcfcTo + 47
    8   UIKitCore                           0x0000000112501166 -[UIClassSwapper initWithCoder:] + 246
    9   UIFoundation                        0x00000001101e55ad UINibDecoderDecodeObjectForValue + 749
    10  UIFoundation                        0x00000001101e52b3 -[UINibDecoder decodeObjectForKey:] + 251
    11  UIKitCore                           0x00000001125057b8 -[UIRuntimeConnection initWithCoder:] + 178
    12  UIFoundation                        0x00000001101e55ad UINibDecoderDecodeObjectForValue + 749
    13  UIFoundation                        0x00000001101e5854 UINibDecoderDecodeObjectForValue + 1428
    14  UIFoundation                        0x00000001101e52b3 -[UINibDecoder decodeObjectForKey:] + 251
    15  UIKitCore                           0x0000000112503067 -[UINib instantiateWithOwner:options:] + 1220
    16  UIKitCore                           0x0000000112276452 -[UIViewController _loadViewFromNibNamed:bundle:] + 383
    17  UIKitCore                           0x0000000112276ddc -[UIViewController loadView] + 177
    18  UIKitCore                           0x00000001122770ee -[UIViewController loadViewIfRequired] + 175
    19  UIKitCore                           0x0000000112277940 -[UIViewController view] + 27
    20  MyApp           0x0000000106dcd12a $S24MyApp19StepsViewControllerC20initialConfiguration33_8FADDC2BAB07508181BB037CD30FE9BDLLyyF + 2122
    21  MyApp            0x0000000106dcc841 $S24MyApp19StepsViewControllerC11viewDidLoadyyF + 97
    22  MyApp            0x0000000106dcc8c4 $S24MyApp19StepsViewControllerC11viewDidLoadyyFTo + 36
    23  UIKitCore                           0x00000001122774e1 -[UIViewController loadViewIfRequired] + 1186
    24  UIKitCore                           0x0000000112277940 -[UIViewController view] + 27
    25  UIKitCore                           0x0000000112a36775 __67-[UIStoryboardEmbedSegueTemplate newDefaultPerformHandlerForSegue:]_block_invoke + 180
    26  UIKitCore                           0x0000000112a387fb -[UIStoryboardSegueTemplate _performWithDestinationViewController:sender:] + 276
    27  UIKitCore                           0x0000000112a386b9 -[UIStoryboardSegueTemplate _perform:] + 82
    28  UIKitCore                           0x0000000112a3897b -[UIStoryboardSegueTemplate perform:] + 157
    29  UIKitCore                           0x00000001122772cd -[UIViewController loadViewIfRequired] + 654
    30  UIKitCore                           0x0000000112277940 -[UIViewController view] + 27
    31  UIKitCore                           0x00000001121c1a9b -[UINavigationController _startCustomTransition:] + 931
    32  UIKitCore                           0x00000001121d83f0 -[UINavigationController _startDeferredTransitionIfNeeded:] + 741
    33  UIKitCore                           0x00000001121d97e0 -[UINavigationController __viewWillLayoutSubviews] + 150
    34  UIKitCore                           0x00000001121b9600 -[UILayoutContainerView layoutSubviews] + 217
    35  UIKitCore                           0x0000000112d80795 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1441
    36  QuartzCore                          0x0000000108ab9b19 -[CALayer layoutSublayers] + 175
    37  QuartzCore                          0x0000000108abe9d3 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 395
    38  QuartzCore                          0x0000000108a377ca _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 342
    39  QuartzCore                          0x0000000108a6e97e _ZN2CA11Transaction6commitEv + 576
    40  UIKitCore                           0x0000000112890701 _UIApplicationFlushRunLoopCATransactionIfTooLate + 165
    41  UIKitCore                           0x000000011298a569 __handleEventQueueInternal + 6874
    42  CoreFoundation                      0x000000010998b721 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    43  CoreFoundation                      0x000000010998b054 __CFRunLoopDoSources0 + 436
    44  CoreFoundation                      0x000000010998563f __CFRunLoopRun + 1263
    45  CoreFoundation                      0x0000000109984e11 CFRunLoopRunSpecific + 625
    46  GraphicsServices                    0x000000010fea91dd GSEventRunModal + 62
    47  UIKitCore                           0x000000011289681d UIApplicationMain + 140
    48  MyApp           0x0000000106df9cb7 main + 71
    49  libdyld.dylib                       0x000000010b6de575 start + 1
    50  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
Cristik
  • 30,989
  • 25
  • 91
  • 127
user308123
  • 135
  • 1
  • 12
  • What is the exact text of the error that is displayed in the console when it crashes? – user1118321 Jan 17 '19 at 05:29
  • It says THREAD_BAD ACCESS – user308123 Jan 17 '19 at 05:29
  • Can you paste the entire text of the error message into your question? (And I mean everything including the hexadecimal address where the bad access occurred.) – user1118321 Jan 17 '19 at 05:31
  • ok @user1118321...just a min.. – user308123 Jan 17 '19 at 05:32
  • it might be Crash due to deadlock From required init?(coder aDecoder: NSCoder) it call commonInit and from commonInit init?(coder aDecoder: NSCoder) call due to loadNibNamed. Please check it after remove commonInit from require init – Jatin Kathrotiya Jan 17 '19 at 05:38
  • I've added the crash log @user1118321..Also it's not a BAD_ACCESS error...sorry..:) – user308123 Jan 17 '19 at 05:39
  • Tried removing commonInit from require init @JatinKathrotiya...but still it crashes with the same error... – user308123 Jan 17 '19 at 05:42
  • There is consistency problem inside the .xib. Examine carefully the content of it, something is wrong (class of some object?). – Jean-Baptiste Yunès Jan 17 '19 at 05:51
  • Please check module in xib is it your target or empty ? just below class name – Jatin Kathrotiya Jan 17 '19 at 06:01
  • No @Jatin Kathrotiya...it is correctly given... – user308123 Jan 17 '19 at 06:04
  • checked that also @Jean-Baptiste Yunès...created a new xib altogether..but it still crashes... – user308123 Jan 17 '19 at 06:05
  • Seems to have a lot of confusion here. At least don't instantiate `VerificationCodeView` by yourself. Either instantiate it OR load it through xib, not both! – Jean-Baptiste Yunès Jan 17 '19 at 06:10
  • ok @Jean-Baptiste Yunès...so u r saying this line `loadingView = VerificationCodeView(frame: verificationCodeView1.frame)` in `viewDidLoad` isn't needed..? – user308123 Jan 17 '19 at 06:21
  • No I am saying that it is not clear how you want to proceed. Read something like https://stackoverflow.com/questions/863321/how-to-load-a-uiview-using-a-nib-file-created-with-interface-builder or https://medium.com/@brianclouser/swift-3-creating-a-custom-view-from-a-xib-ecdfe5b3a960 which seems to be very similar to what you did... The nastiest thing here is the call to loadFromNib inside the view that you want to load... – Jean-Baptiste Yunès Jan 17 '19 at 07:59

3 Answers3

0

Please Update your function

private func commonInit() {
let uvNub: UIView = Bundle.main.loadNibNamed("VerificationCodeView", owner: self, options: nil) //CRASHES HERE
self.addSubview(uvNub)
contentView.frame = self.bounds
contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth]

}

Parth Dhorda
  • 712
  • 1
  • 8
  • 32
  • I tried it @Parth Dhorda...but at this line `let uvNub: UIView = Bundle.main.loadNibNamed("VerificationCodeView", owner: self, options: nil) `it shows the error `Cannot convert value of type '[Any]?' to specified type 'UIView'` – user308123 Jan 17 '19 at 05:47
0

Try below code,

fileprivate func commonInit() {

    let bundle = Bundle(for: type(of: self))
    bundle.loadNibNamed("VerificationCodeView", owner: self, options: nil)
    self.addSubview(containerView)
    containerView.translatesAutoresizingMaskIntoConstraints = false
    containerView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 0).isActive = true
    containerView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: 0).isActive = true
    containerView.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true
    containerView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true
}
Ahemadabbas Vagh
  • 492
  • 3
  • 15
0

I found something wrong in your code.

  1. You have an outlet for contentView. This means this view is already added to your view hierarchy. Then in your commonInit() 'addSubview(contentView)' is wrong to do.

  2. The result of Bundle.main.loadNibNamed("VerificationCodeView", owner: self, options: nil) is unused.

You can use this to load a view from nib:

let verificationCodeView = UINib(nibName: "VerificationCodeView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! VerificationCodeView

If you want to get an instance of VerificationCodeView, then write a class method like below.

class func instantiateFromNib() -> VerificationCodeView {

    let verificationCodeView = UINib(nibName: String(describing:self), bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! VerificationCodeView
    return verificationCodeView
}

Now, whenever you want this view just get it like below:

let verificationCodeView = VerificationCodeView.instantiateFromNib()
Shubham
  • 763
  • 5
  • 20