2017-08-29 62 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

相关问题