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

Posted

技术标签:

【中文标题】如何在 Objective C 中以编程方式设置集合视图?【英文标题】:How to set collection view programmatically in Objective C? 【发布时间】:2017-08-29 12:18:47 【问题描述】:

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

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?

【问题讨论】:

这就是你想要的,见***.com/questions/17856055/… 【参考方案1】:

也许我还没有明白你想要达到什么目的......

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

【讨论】:

谢谢。我现在编辑代码错误消失了。这是正确的方法吗? self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:[控制器 initWithCollectionViewLayout:layout]];

以上是关于如何在 Objective C 中以编程方式设置集合视图?的主要内容,如果未能解决你的问题,请参考以下文章

如何在Objective-C中以编程方式发送带有一些正文文本的短信[重复]

如何在Objective-C中以编程方式而不是由用户控制UISwitch的状态?

如何在 Objective-C 中以编程方式添加特定大小的 UIImageView。我也有同一个类的 xib 文件,但我不想使用它

在 Objective-C Xcode 5 中以编程方式创建视图

如何在 Objective-C 控制器中以编程方式加载用 swift 编写的自定义 XIB 视图

如何在应用程序委托iOS10 Objective C中的applicationWillEnterForeground方法中以模态方式呈现UIViewController