Reputation: 454
I am trying to add a custom UIView to a view controller. I have done this before and had no issues so I'm very confused here.
I have configured file owners correctly, have all required init methods, etc set up for the custom view. Nothing seems out of place to me and everything configured exactly as before.
When I run the code, neither of the custom views init methods are called (placed breakpoints on both). When I add the custom view as an IBOutlet into my view controller, I get an error saying:
"Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value".
This comes from a line in my viewcontroller attempting to change a colour of the custom view. I assume because the view hasn't been initialised so it returns nil.
So any ideas on why this custom view isn't being initialised?
ViewController:
class ProductSearchViewController: UINavigationController {
@IBOutlet weak var mainSearchView: MainSearchView!
override func viewDidLoad() {
super.viewDidLoad()
applyTheme()
setupNavigationBar()
// Do any additional setup after loading the view.
}
func applyTheme() {
self.view.backgroundColor = UIColor.init(named: "appPrimaryColour")
self.mainSearchView.backgroundColor = UIColor.yellow
}
func setupNavigationBar() {
self.title = NSLocalizedString("product.search.tab.bar.item.title", comment: "")
self.navigationBar.isHidden = true
}
}
Custom View:
import UIKit
class MainSearchView: UIView {
@IBOutlet var contentView: UIView!
@IBOutlet weak var searchBar: UITextField!
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
let xib = UINib(nibName: "MainSearchView", bundle: nil)
xib.instantiate(withOwner: self, options: nil)
addSubview(contentView)
contentView.frame = self.bounds
contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
contentView.backgroundColor = UIColor.blue
}
}
Upvotes: 0
Views: 668
Reputation: 91
ProductSearchViewController is extended from UINavigationController, If it will get extended from UIViewController your problem will get solved.
Upvotes: 1