2017-08-29 59 views
0

我是新手想了解如何設置集合視圖編程如何在Objective C中以編程方式設置集合視圖?

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

我想獲得上述目的C. SWIFT代碼我迄今所做低於錯誤結果中列出。爲了達到上述目的,我必須在objc代碼中做出哪些改變。

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? 
+0

這爲u想要什麼,看https://stackoverflow.com/questions/17856055/creating-a-uicollectionview-programmatically –

回答

0

也許你想達到什麼我一直搞不明白......

你需要的是一個自定義的init方法添加到您的ViewController。例如:

// 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 

您可以使用如下代碼:

[[HomeViewController alloc] initWithCollectionViewLayout:yourLayout]; 

否則,而不是使用一個構造器注入,你可以做一個屬性注入。

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

@property (nonatomic, strong) UICollectionViewLayout* collectionViewLayout; 

@end 

而且使用這樣的代碼:

HomeViewController* vc = [[HomeViewController alloc] init]; 
vc.collectionViewLayout = yourLayout; 
+0

感謝。我編輯的代碼現在錯誤消失了。這是正確的方法嗎? self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:[controller initWithCollectionViewLayout:layout]]; – ios

相關問題