[英]How to set collection view programmatically in Objective C?
我是一個新手,試圖學習如何以編程方式設置集合視圖
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?
也許我不明白你想要實現什么...
您需要的是向ViewController
添加自定義init方法。 例如:
// 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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.