简体   繁体   中英

xib-specified location moves on UIView load?

I have a couple of view controllers that I want all to share a header status bar. This header view shows status of certain things in my app. I used IB to lay out the contents of the header view in its own xib, then also used IB to layout the view controllers, adding a placeholder UIView element in the view controller's xibs for when I load in the header programmatically.

Now, when I create a UIView subclass from the contents of the view xib, and add that as a subview to the view of any of my view controllers, the location that I specified for the header view in my view controller xib seems to get ignored, and the header view gets placed at (0,0) no matter what. All the contents of the header view load and appear fine, it's just the location of the header view in the view controller that is wrong.

Here's how I'm loading and adding my header view to my view controller:

header = [InfoHeader loadFromNib:MY_NIB_NAME withOwner:self];
[self.view addSubview:header];

The view controller xib is confirmed to have an outlet connected to the 'header' variable. And here's that 'loadFromNib' method:

+(InfoHeader *) loadFromNib: (NSString *) nibName withOwner:(id) objectOwner
{
    NSBundle *b = [NSBundle mainBundle];
    NSArray *nib = [b loadNibNamed:nibName owner:objectOwner options:nil];

    InfoHeader *header;

    for (id obj in nib)
    {
        if ([obj isKindOfClass:[InfoHeader class]])
        {
            header = (InfoHeader *) obj;
        }
    }

    return header;
}

Any ideas on what to check here? I'd rather not locate the header bar programmatically, but let IB do it.

Did you change the location of your subview in IB? Usually, the default location (0, 0) of the view will be the (top, left) coordinate of the big view in the screen. I think checking that will work fine

You can do this without using a "placeholder" view at all, by programmatically specifying the frame of the subview:

InfoHeader *header = [InfoHeader loadFromNib:MY_NIB_NAME withOwner:self];
header.frame = CGRectMake(0, 44, header.frame.size.width, header.frame.size.height);
[self.view addSubview:header];

(that code asssumes that you have removed the header outlet from your class, so it can be a local variable instead).

Or, if you'd rather use the placeholder (so you can specify the header's position using IB instead of programmatically), do it like this:

InfoHeader *headerView = [InfoHeader loadFromNib:MY_NIB_NAME withOwner:self];
[header addSubview:headerView];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM