覆盖initWithCoder时的无限循环 [英] Infinite loop when overriding initWithCoder

查看:98
本文介绍了覆盖initWithCoder时的无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有一些控制器和一些视图的 UIViewController 。其中两个视图(Grid Cell)是其他nib。我有从网格单元到文件所有者的出口,但它们没有自动加载。

I have a UIViewController with some controllers and some views. Two of these views (Grid Cell) are other nibs. I've got outlets from the Grid Cells to File's Owner, but they aren't loaded automatically.

所以我尝试覆盖 GridCell.m initWithCoder
这会启动无限循环。

So I try to override GridCell.m's initWithCoder. This starts an infinite loop.

我知道可以覆盖 initWithFrame 并添加子视图从代码,但这不是我想要的。我希望能够在Interface Builder中移动视图,让Xcode用正确的框架初始化视图。

I know it's possible to just override initWithFrame and add the subview from code, but this is not what I want. I want to be able to move the view around in Interface Builder and have Xcode initialize the view with the right frame.

我如何实现这一目标?

编辑1

我正试图让它在亚历山大的帮助下工作。这就是我现在设置它的方式:
MainView将UIView的Custom类设置为GridCell。它在MainView / File的所有者中有一个插座。

I'm trying to get it working with the help of Alexander. This is how I've now got it set up: MainView has UIView with a Custom class set as GridCell. It got an outlet in the MainView/File's Owner.

从GridCell.m中删除所有初始化代码并设置我的自定义类的插座

Removed all init-code from GridCell.m and set up an outlet to my custom class

MainView不会显示GridCell。没有错误,只是一个孤独的,空的空间,红色开关应该是。我做错了什么?

The MainView don't still display the GridCell though. There's no error, just a lonely, empty space where the red switch should be. What am I doing wrong?

我非常接近于以编程方式执行此操作。我很想学习如何使用笔尖。

I'm very close to just doing this programmatically. I would love to learn how to this with nibs though.

推荐答案

加载笔尖会导致再次调用initWithCoder,所以你只能如果子类当前没有任何子视图,则希望这样做。

Loading the nib causes initWithCoder to be called again, so you only want to do so if the subclass currently doesn't have any subviews.

-(id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        if (self.subviews.count == 0) {
            UINib *nib = [UINib nibWithNibName:NSStringFromClass([self class]) bundle:nil];
            UIView *subview = [[nib instantiateWithOwner:self options:nil] objectAtIndex:0];
            subview.frame = self.bounds;
            [self addSubview:subview];
        }
    }
    return self;
}

这篇关于覆盖initWithCoder时的无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆