Where to put .xib file inside framework project?

后端 未结 2 580
天命终不由人
天命终不由人 2021-02-05 16:05

I lost half a day figuring this and I can\'t see a straight forward solution online.

I created an iOS CocoaTouch Framework. I have some private and public classes in it

相关标签:
2条回答
  • 2021-02-05 16:42

    Where to Put Nib Files within a Framework in iOS Project?

    Background to my answer:
    I was trying to export some UITableView related implementation and it had UITableViewCell .xib files packed with it. And they turn into .nib files at the end! ;-) And I was referring to those Nib files as follows:

    [[NSBundle mainBundle] loadNibNamed:customCellID owner:nil options:nil];
    

    Explanation:
    But here the thing I have done wrong is, I build a static Cocoa Touch Framework and try to use it within another Application. So at the run time what would become the MainBundle? Definitely my UITableView implementation trying to find out that Nib file for the customCellID in within the App's main bundle.

    Answer:
    So I altered my UITableView implementation's above code snippet as follows:

        NSString *frameworkBundleId = @"com.randika.MyFrameworkBundleIDHere";
        NSBundle *resourcesBundle = [NSBundle bundleWithIdentifier:frameworkBundleId];
    
        customCell = (CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:customCellID];
        if (customCell == nil) {
           NSArray *nibs = [resourcesBundle loadNibNamed:emptyCellID owner:nil options:nil];
           customCell = [nibs objectAtIndex:0];
        }
    

    And the framework I built out of my UITableView implementation didn't give the above error ever again! :-)

    Hope this answer might be helpful to somebody out there!

    Cheers! :-)

    0 讨论(0)
  • 2021-02-05 16:57

    Generic solution for controllers with .xib file

    public extension UIViewController {
    
        //** loads instance from right framework bundle, not main bundle as UIViewController.init() does
        private static func genericInstance<T: UIViewController>() -> T {
            return T.init(nibName: String(describing: self), bundle: Bundle(for: self))
        }
    
        public static func instance() -> Self {
            return genericInstance()
        }
    }
    

    Use as

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