如何在 Objective C 中以编程方式设置集合视图?

How to set collection view programmatically in Objective C?

我是新手,正在尝试学习如何以编程方式设置集合视图

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

我正在努力超越 Objective 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?

可能我没明白你要达到什么目的...

您需要为 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;