0

我有这两段代码。第一个完美运行:

UIView *tmp = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 60.0f, 296.0f, 44.0f)];
[self.dynamicView addSubview:tmp];
[tmp release];

第二个几乎相同,但视图不显示。

CommentBox *commentBox = [[CommentBox alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 296.0f, 44.0f)]; 
[self.dynamicView addSubview:commentBox];
[commentBox release];   // Why does this remove the view?

如果我删除该[commentBox release]视图,则会出人意料地出现。但我看不出这两个代码片段有什么不同。

CommentBox 的初始化如下所示:

- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
        // Load the nib:
        NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"CommentBox" owner:self options:nil];
        self = [nibObjects objectAtIndex:0];

    }
    return self;
}
4

2 回答 2

3

在考虑了格雷厄姆的回答后,我想出了以下解决方案:

  1. 我在我的主 UIView 的 Interface Builder 中拖动了一个新的 UIView(-> 让我们称之为子 UIView)
  2. 我给这个子 UIView 正确的大小(因为我无法调整主 UIView 的大小,它总是 320x460)
  3. 我在这个子 UIView 中拖动所有其他元素(以便所有元素都附加到我的子 UIView)
  4. 我给我的子 UIView 一个标签号(Interface Builder -> View Attributes),例如“300”
  5. 在代码中,我现在在我的-initWithFrame:

    NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"CommentBox" owner:self options:nil]; UIView *subView = [[nibObjects objectAtIndex:0] viewWithTag:300]; [自我添加子视图:子视图];

希望有帮助。


更新:

我只是有了另一个想法。除了标签号,您还可以IBOutlet UIView *viewHolderCommentBox类中创建一个并在 IB 中设置出口。然后在initWithFrame:我执行以下操作:

[[NSBundle mainBundle] loadNibNamed:@"CommentBox" owner:self options:nil];
[self addSubview:self.viewHolder];
于 2010-05-19T10:12:20.033 回答
2
于 2010-05-19T08:58:19.437 回答