Legonaftik
Legonaftik

Reputation: 1390

Cannot cast my custom UIView subclass created from XIB to the class I need (only UIView)

What I've done is:

1) Created a .xib file TranslationInfoWindow.xib:

xib file for the info window

2) Created TranslationInfoWindow.swift file with the follow content:

import UIKit

class TranslationInfoWindow: UIView {

    // MARK: - Initializers

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

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

    // MARK: - Private Helper Methods

    // Performs the initial setup.
    private func setupView() {
        let view = viewFromNibForClass()
        view.frame = bounds

        // Auto-layout stuff.
        view.autoresizingMask = [
            UIViewAutoresizing.flexibleWidth,
            UIViewAutoresizing.flexibleHeight
        ]

        // Show the view.
        addSubview(view)
    }

    // Loads a XIB file into a view and returns this view.
    private func viewFromNibForClass() -> UIView {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
        let view = nib.instantiate(withOwner: self, options: nil).first as! UIView

        return view
    }

    @IBOutlet weak var avatarImageView: RoundedImageView!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var usersLabel: UILabel!
}

3) Here I try to initialise my custom view:

func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? {
    //             FIXME: There is a UIView but it doesn't want to be casted in TranslationInfoWindow
    if let infoWindow = Bundle.main.loadNibNamed(
        "TranslationInfoWindow", owner: view, options: nil)?.first as? TranslationInfoWindow {
        return infoWindow
    } else {
        return nil
    }
}

Now if I try to run the project I have the following error: My error

What am I doing wrong?


UPDATE:

Here's the hierarchy of xib: enter image description here

Upvotes: 2

Views: 1111

Answers (2)

ovidiur
ovidiur

Reputation: 338

You should set the correct class of TranslationInfoWindow.xib to be type TranslationInfoWindow in IB .

Upvotes: 0

HammondSuisse
HammondSuisse

Reputation: 143

In Interface Builder, did you change the class name in the Identity Inspector (3rd from left) tab from UIView to your custom class name? screen grab of IB

Upvotes: 2

Related Questions