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?
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.