【发布时间】:2011-03-16 19:48:48
【问题描述】:
我可能没有正确执行此操作。在我做对我来说很自然的事情之前,我还没有做过 iPad 应用程序。
我有一个 UIView,它将由其他 UIView 组成。具体来说,我想动态地创建子视图并将其添加到每个子视图。换句话说:
UIView
|
| --> UIView
|
| --> Dynamic UIView 1
| --> Dynamic UIView 2
| --> ...
我设法通过在它的 initWithFrame 中添加这段代码来加载 xib 来获得“动态 UIView 1”:
NSArray *nibViews = [[NSBundle mainBundle] loadNibNamed:@"ItemView"
owner:[[ItemViewController alloc] init]
options:nil];
ItemView *infoView = [nibViews objectAtIndex:0];
[self addSubview:infoView];
有效!我遇到的问题是“动态 UIView n”总是呈现在屏幕的左上角。如果我尝试使用 setFrame 更改位置,我会在表示框架时得到一个黑框,但实际的控件内容仍保留在左上角。
有什么想法吗?有没有更好的方法来做到这一点?
----- 更新-----
这是根视图的屏幕截图。 Overview of main UIView http://www.freeimagehosting.net/uploads/460090996d.png
整个控件是调用CurrentItemsViewController。绿色区域是一个 UIView,我通过 IB 中的链接将其链接回代码中,在代码示例中它被称为“itemsUIView”。这是我在 CurrentItemsViewController.m 中添加项目的方式
- (id)init {
[super initWithNibName:nil
bundle:nil];
UITabBarItem *tbi = [self tabBarItem];
[tbi setTitle:@"Current"];
/* Approach 1 */
NSArray *nibViews = [[NSBundle mainBundle] loadNibNamed:@"ItemView"
owner:[[ItemViewController alloc] init]
options:nil];
ItemView *subItemView1 = [nibViews objectAtIndex:0];
/* Approach 2 - this apprach does Approach 1 in the initWithFrame method */
//ItemView *subItemView1 = [[ItemView alloc] initWithFrame:CGRectMake(120, 120, 354, 229)];
/* Approach 3 */
//ItemViewController *ctr = [[ItemViewController alloc] init];
//UIView *subItemView1 = [ctr view];
[[self view] addSubview:subItemView1];
// [[self itemsUIView] addSubview:subItemView1]; <-- doesn't render subItemView1 at all
[subItemView1 release];
[subItemView1 setFrame:CGRectMake(120, 120, 354, 229)];
[subItemView1 setBounds:CGRectMake(120, 120, 354, 229)];
return self;
}
在 ItemView.m 里面我有这个,它只被方法 2 和 3 调用。
- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
NSArray *nibViews = [[NSBundle mainBundle] loadNibNamed:@"ItemView"
owner:[[ItemViewController alloc] init]
options:nil];
ItemView *infoView = [nibViews objectAtIndex:0];
[self addSubview:infoView];
}
return self;
}
如图所示,我尝试了 3 种不同的方式创建 ItemView,每一种都呈现相同的结果。当我将视图添加为根视图的子视图时,我得到了这个。请注意,一个正方形出现在它应该呈现的位置,但 ViewItem 实际上呈现在左上角。在上面的示例中,当我添加 subItemView1 时,它根本不会呈现任何内容。
alt text http://www.freeimagehosting.net/uploads/c6635ce860.png
【问题讨论】:
-
请提供更多细节:截图、
initWithFrame:的完整代码、setFrame代码... -
如果您想要更多,请告诉我。
标签: iphone ipad uiview xib nsbundle