0

I am trying to add a subview in a viewController. To perform that I have created an xib file and an associated class. The code of the associated class is given below:

import UIKit

@IBDesignable class CustomClassViewController: UIView {

@IBOutlet weak var myLabel: UILabel!

var Dummyview : UIView! //= UIView()

override init(frame: CGRect) {
    super.init(frame: frame)
    setup()  
}

required init (coder aDecoder : NSCoder){

    super.init(coder : aDecoder)!
    setup()
}

func setup() {
    Dummyview =  loadViewFromNib()
    Dummyview.frame = bounds
    Dummyview.autoresizingMask = UIViewAutoresizing.FlexibleWidth
    Dummyview.autoresizingMask =  UIViewAutoresizing.FlexibleHeight
    addSubview(Dummyview)
}

func loadViewFromNib() -> UIView {
    let bundle = NSBundle(forClass : self.dynamicType)
    let nib = UINib(nibName: "Custom View", bundle: bundle)
    let view = nib.instantiateWithOwner(self, options: nil)[0] as! UIView
    return view   
}

It shows no Error before run the application but it crash when I run the application. The Error shows as below:

"Threat 1: EXC_BAD_ACCESS(code= 2, address= 0x7fff52776e88)"

super.init(coder : aDecoder)!

But no Errors in Output.

I have tried the solution provided in here and here but not worked.

What should I do? Any solution? Please let me know. Thanks in advance

Community
  • 1
  • 1
Faisal Mirza
  • 63
  • 1
  • 12

2 Answers2

0

Init with coder can fail, you shouldn't use force unwrap there. Try the following:

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

Also your class CustomClassViewController is a subclass of the UIView and not the UIViewController. Change this line

@IBDesignable class CustomClassViewController: UIView {

to

class CustomClassViewController: UIViewController {

Note: A view controller cannot be IBDesignable

Istvan
  • 1,627
  • 1
  • 11
  • 17
  • Thanks for the comments. i tried your provided solution but it didn't worked for me. Another Things If i don't declare the class as @IBDesignable then it will not show in my view controller as a subview – Faisal Mirza Nov 08 '16 at 09:06
  • Whay do you mean "it will not show in my view controller as a subview" Please learn how to use IBDesignable first. Here is a really good article: http://nshipster.com/ibinspectable-ibdesignable/ An UIViewController cannot be IBDesignable. You are confusing the view and the ViewController. What do you want exactly? An IBDesignable UIView, or a UIViewController? – Istvan Nov 08 '16 at 09:13
0

The nib shouldn't have a class set in interface builder. Otherwise you'll get an infinite loop as your class tries to instantiate itself every time it calls that nib.

When you want to use this view template in your storyboard you pull in a view and set that to your custom view class.

Aquila Sagitta
  • 438
  • 3
  • 9