Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

how to initialise view controller in code and use interface builder

in interface builder i set up a tabBarController which is my root view controller. However, i am following the photo bombers tutorial code where I change the init method to set up my collection view in one of my tabs and it sets this to the rootviewcontroller resetting all my work in interface builder. is there a way of initialising the collectionviewcontroller without setting it as my root view controller and maintaining my tab bar?

thanks!

any ideas Sam Soffes ?

2 Answers

I've managed to set up a CollectionViewController as one of the tabs like so:

FirstViewController.h

#import <UIKit/UIKit.h>
@interface FirstViewController : UICollectionViewController
@end

FirstViewController.m

#import "FirstViewController.h"
@interface FirstViewController ()
@end

@implementation FirstViewController
- (instancetype)init {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(106.0, 106.0);
    layout.minimumInteritemSpacing = 1.0;
    layout.minimumLineSpacing = 1.0;
    return [self initWithCollectionViewLayout:layout];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"photo"];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.title = @"Photo Bombers";
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 10;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"photo" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor grayColor];
    return cell;
}

@end

Works like a charm. You still need to tweak the spacing on top though.

I ended up alerting the method initWithCoder and putting the layout constraints in there and then calling it:

UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
    HomeViewController *vc = (HomeViewController *) [storyBoard instantiateViewControllerWithIdentifier:@"Home"];

    [vc initWithCoder:nil];

thanks for the help though!