我是一个新手试图学习如何以编程方式设置集合视图
let layout = UICollectionViewFlowLayout()
window?.rootViewController = UINavigationController(rootViewController : HomeController(collectionViewLayout:layout))
我正试图在目标C中获得上面的快速代码。到目前为止,我所做的工作在下面列出了错误结果。我需要在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 :(得分:0)
也许我不明白你想要达到的目标......
您需要为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;