1

I want to create two side by side views to add to my viewcontroller's view. To keep from repeating code, I am trying to write a generic method to create the two views for me. However, this code isn't working for me. Both view1 and view2 are ivars.

- (void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];

  [self makeView:view1];
  [self makeView:view2];
}

- (void)makeView:(UIView*)view {
  CGRect frame = self.view.bounds;
  frame.size.height = frame.size.height/2;
  if (view == view2) {
    frame.origin = CGPointMake(0, frame.size.height);
  }
  view = [[UIView alloc] initWithFrame:frame];
  [self.view addSubview:view];
}

I think the issue might deal with the line view == view2, some sort of variable reference error. view == view2 always evaluates to true, so view1 never shows up. And in later parts of the code view1 and view2 are nil.

4

3 回答 3

1

让我们一步一步来找出答案。

首先,你viewWillAppear被调用,并且view1两者view2都是nil因为你还没有将它们设置为任何东西。

然后,您正在调用您的方法 on view1nil也就是说,参数将是 value nil

您创建框架,然后进入您的 if 语句。参数 ( view) 是nil,正如我们之前所说的,view2也是nil因为,正如我们之前所说,它开始于nil并且我们尚未将其设置为任何内容。正因为如此,view==view2是真的,因为nil==nil是真的,你得到了你想要的 view2 的原点的框架。

然后,您正在设置view一个新的 UIView 并将其添加到子视图中,该子视图确实添加了视图(您想要的 view2),但您仍然没有设置view1变量。

在此之后,您正在对 执行完全相同的操作view2,这会为您提供具有完全相同框架的另一个视图,因为viewview1view2都是静止的nil

为了绕过这一点,您实际上应该在该方法( )之外进行创建,view1并且只在该方法内部进行所有设置部分。view2view1/2 = [[UIView alloc] init];

于 2013-08-19T22:36:44.937 回答
0

如果它们还没有被分配,你将为 view1 和 view2 传递一个 nil 指针,然后与一个 nil 指针进行比较,这总是正确的。运行时看到 if(nil == nil)。尝试这样的事情:

- (void)viewWillAppear:(BOOL)animated {
  [super viewWillAppear:animated];

  view1 = [[UIView alloc] init];
  view2 = [[UIView alloc] init];

  [self makeView:view1];
  [self makeView:view2];
}

- (void)makeView:(UIView*)view {
  CGRect frame = self.view.bounds;
  frame.size.height = frame.size.height/2;
  if (view == view2) {
    frame.origin = CGPointMake(0, frame.size.height);
  }
  [view setFrame:frame];
  [self.view addSubview:view];
}
于 2013-08-19T22:35:44.087 回答
0

这是指针的问题。试试这个:

- (void)testExample
{
    object = [NSObject new];
    NSLog(@"Address 1: %p", object);
    [self method:object];
}

- (void) method:(NSObject*) _object {
    NSLog(@"Address 2: %p", _object);
    _object = [NSObject new];
    NSLog(@"Address 3: %p", _object);
    NSLog(@"Address 4: %p", object);
}

输出类似于

Address 1: 0xcb98ae0
Address 2: 0xcb98ae0
Address 3: 0x11060950
Address 4: 0xcb98ae0

所以首先你得到对象的指针。然后在method:你得到相同的指针。但是,当您分配一个新对象并将其分配给_objector 时,您view的指针会发生变化,因此您的 ivarsview1view2保持为零。

您必须先分配视图,然后再布局它们。

于 2013-08-19T22:35:56.027 回答