1

i am trying to create a custom UIView in a separate swift file with code like this

import UIKit
class CustomView : UIView {
    var contentView:UIView?
    // other outlets

    override init(frame: CGRect) { // for using CustomView in code
        super.init(frame: frame)
        self.commonInit()
    }

    required init?(coder aDecoder: NSCoder) { // for using CustomView in IB
        super.init(coder: aDecoder)
        self.commonInit()
        fatalError("NSCoding not supported")
    }

    private func commonInit() {
        Bundle.main.loadNibNamed("CustomView", owner: self, options: nil)
        guard let content = contentView else { return }
        content.frame = self.bounds
        content.autoresizingMask = [.flexibleHeight, .flexibleWidth]
        self.addSubview(content)
    }
}

then i call it in a viewcontroller with code like this

var custom:CustomView! = CustomView()

override func viewDidLoad() {
        super.viewDidLoad()



        custom.backgroundColor = UIColor.blue
        view.addSubview(custom)
    }

yet i got an error like this:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle:
(loaded)' with name 'CustomView''

Why do i get this error code? i have look everywhere on youtube, google,even some stackoverflow answer that similar to this. And they all did the same thing as i did but i am the only one that got this error. i dont know what NIB bundle is. and how do make this custom UIView work

3432f32
  • 9
  • 1
  • 2

1 Answers1

0

The name of your xib must match the string you pass in when you load it: Bundle.main.loadNibNamed("CustomView", owner: self, options: nil)

You are saying here that the name of your xib in your project is CustomView. Check that it has that name in Xcode s project navigatior, like this:

Project Navigator XIB name

If that is correct, ensure that it is installed correctly by opening the File inspector (⌘ + ⌥ + 1 / Command + option + 1) and checking the Target Membership box is checked. Here it is shown as ProjectName right at the bottom:

Checking target membership

Jake
  • 545
  • 2
  • 6
  • sorry if i sound like a noob, but i dont get it why do i need to have .xib file? is there other way that i can make custom UIView without it? – 3432f32 Mar 22 '18 at 00:39
  • The code example you provided indicated you were trying to load a xib file that you had already created. There are three options for making a custom view subclass: Interface builder using a xib, interface builder inside a storyboard, or programatically (all code, no interface builder). – Jake Mar 22 '18 at 00:44
  • how do i do it programatically? – 3432f32 Mar 22 '18 at 01:30
  • [Here is examples of creating custom views](https://github.com/codepath/ios_guides/wiki/Custom-Views). It includes code examples of creating a view programatically as well as using interface builder. The 4th heading is creating a view programatically. – Jake Mar 22 '18 at 02:03