繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM