Could not cast value of type UIView to [CustomView] using Xib

前端 未结 4 1243
予麋鹿
予麋鹿 2021-01-24 09:11

I\'ve seen a number of similar questions, but many aren\'t up-to-date, and none have fixed my issue.

I have a custom Xib and class, CardView. When I try to

相关标签:
4条回答
  • 2021-01-24 09:28

    In case someone still having this problem, I have the same problem and I think we follow same tutorial.

    You have called loadNib() in your xibSetup(). I think you don't have to call it again.

    So instead of using

    let myCardView = CardView().loadNib() as! CardView
    

    I just use

    let myCardView = CardView()
    
    0 讨论(0)
  • 2021-01-24 09:33

    For me loading xib programmatically in this way doesn’t work. I had to remove File owner’s class name and set that to the class name of first view. And then I had to set outlets to the components which I’m going to use.

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

    Added to custom view class after outlets. For you it's CardView. Then I loaded that view class like

    let viewCard = Bundle.main.loadNibNamed("CardView", owner: self, options: nil)?.first as! CardView
    view.addSubview(viewCard)
    
    0 讨论(0)
  • 2021-01-24 09:37

    In your UIViewController, when you create an instance of your CardView, instead of casting it like CardView().loadNib() as! CardView, you call the function object_setClass(_, _) to avoid that error (from Xcode 9).

    So it should be like:

    let myCardView = CardView().loadNib
    object_setClass(myCardView, CardView.self)
    view.addSubview(myCardView)
    
    0 讨论(0)
  • 2021-01-24 09:37

    Old question, but in case anyone's here:

    My problem was that the view subclass was fileprivate. IB doesn't like that apparently.

    0 讨论(0)
提交回复
热议问题