How to embed a custom view xib in a storyboard scene?

前端 未结 11 652
生来不讨喜
生来不讨喜 2021-01-29 21:33

I\'m relatively new in the XCode/iOS world; I\'ve done some decent sized storyboard based apps, but I didn\'t ever cut me teeth on the whole nib/xib thing. I want to use the sam

11条回答
  •  粉色の甜心
    2021-01-29 22:01

    It's been a while on this one, and I've seen a number of answers go by. I recently revisited it because I had just been using UIViewController embedding. Which works, until you want to put something in "an element repeated at runtime" (e.g. a UICollectionViewCell or a UITableViewCell). The link provided by @TomSwift led me to follow the pattern of

    A) Rather than make the parent view class be the custom class type, make the FileOwner be the target class (in my example, CycleControlsBar)

    B) Any outlet/action linking of the nested widgets goes to that

    C) Implement this simple method on CycleControlsBar:

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        if let container = (Bundle.main.loadNibNamed("CycleControlsBar", owner: self, options: nil) as? [UIView])?.first {
            self.addSubview(container)
            container.constrainToSuperview() // left as an excise for the student
        }
    }
    

    Works like a charm and so much simpler than the other approaches.

提交回复
热议问题