0

I am a newbie trying to learn how to set collection view programatically

let layout = UICollectionViewFlowLayout()    
window?.rootViewController = UINavigationController(rootViewController : HomeController(collectionViewLayout:layout))

I am trying to get above swift code in Objective C. What I have done so far is listed below results in error. What are the changes i have to make in objc code to achieve above.

ViewController *controller = [[ViewController alloc] init];  // @interface ViewController : UICollectionViewController  
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init]; 
self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:[controller collectionViewLayout:layout]] ; // ERROR How to set Collection View?
ios
  • 165
  • 1
  • 9

1 Answers1

0

Maybe I have not understand what you want to achieve...

What you need is to add a custom init method to your ViewController. For example:

// In your .h file
@interface HomeViewController : UIViewController

- (instancetype)initWithCollectionViewLayout:(UICollectionViewLayout *)collectionViewLayout;

@end

// In your .m file
@interface HomeViewController ()

@property (nonatomic, strong) UICollectionViewLayout* collectionViewLayout;

@end

@implementation HomeViewController

- (instancetype)initWithCollectionViewLayout:(UICollectionViewLayout *)collectionViewLayout
{
    self = [super init];
    if (self) {
        _collectionViewLayout = collectionViewLayout;
    }
    return self;
}

// Other code here

@end

You can use the code like the following:

[[HomeViewController alloc] initWithCollectionViewLayout:yourLayout];

Otherwise, instead of using a constructor injection, you can do a property injection.

// In your .h file
@interface HomeViewController : UIViewController

@property (nonatomic, strong) UICollectionViewLayout* collectionViewLayout;

@end

And use that code like:

HomeViewController* vc = [[HomeViewController alloc] init];
vc.collectionViewLayout = yourLayout;
Lorenzo B
  • 33,006
  • 23
  • 110
  • 185
  • Thanks . i edited code now errors gone . Is this the correct way? self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:[controller initWithCollectionViewLayout:layout]]; – ios Aug 29 '17 at 12:49