[UIKit] load UIView from Xib(nib)

정유진·2022년 10월 20일
0

swift

목록 보기
14/25
post-thumbnail
post-custom-banner

👹 Intro

Unfortunately when you can not find a nib file from bundle even though you make it clear to initialize with the exact xib file name

the problem is...

if you are in the case that trying to find the nib file in one of that frameworks you imported, your target project might be getting through hard time to get the nib file as it is not in the main bundle from the target project but from the the framework we early mentioned

you can try this solution...

  • let them know which bundle you wanna looking for by identifier
  • make that function as extension so you can use it over and over
extension UIView {
    class func fromNib<T: UIView>() -> T {
        let bundleID = "com.your.bundleID"
        let bundle = Bundle.init(identifier: bundleID)
        let nib = UINib(nibName: String(describing: T.self), bundle: bundle!).instantiate(withOwner: nil, options: nil)[0] as! T
        return nib
    }
}

🐟 Finally

It worked in my case seamleassly. Additionally, do not forget if you initialize your UIView by xib (not by programmatical way) you should override required init(coder:) in your custom UIView. Have a enjoy in your code trip and feedbacks are always welcomed 🐹

profile
느려도 한 걸음 씩 끝까지
post-custom-banner

0개의 댓글