Why can I not manipulate the objects in my xib file?

女生的网名这么多〃 提交于 2019-12-11 09:02:44

问题


I've got a file, View.xib with three UIViews in it, each of the same UIView subclass. The views all look a bit different, but they're going to be used as pages in a tutorial screen, so they have page indicators on the bottom.

I made an outlet collection of the three page indicators on each page. So in the custom UIView I made an outlet collection, and for each of the three views I connected all three page indicators to the outlet collection.

However, in initWithFrame: I do the following:

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        for (UIView *pageIndicator in self.pageIndicators) {
            pageIndicator.layer.cornerRadius = pageIndicator.bounds.size.width / 2;
        }
    }
    return self;
}

(The for loop being the key part.)

But when I add the UIView from the nib in my other file, the indicators are not rounded as the above code should accomplish:

    TutorialScreen *tutorialScreen1 = [[[NSBundle mainBundle] loadNibNamed:@"View" owner:nil options:nil] objectAtIndex:0];
    tutorialScreen1.layer.cornerRadius = 8.0;
    [self.notificationWindow addSubview:tutorialScreen1];

What am I doing wrong?

Sample project where it doesn't work: http://cl.ly/170O2u10181V


回答1:


When an object is read from a nib/xib, it is initialized with initWithCoder:. Override that and do the same thing (or, better yet, move it to a method that both call).

- (void)mySetup
{
    for (UIView *pageIndicator in self.pageIndicators) {
        pageIndicator.layer.cornerRadius = pageIndicator.bounds.size.width / 2;
    }
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self mySetup];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self mySetup];
    }
    return self;
}

After looking at your project, you're suffering from a different problem. You didn't mention you were trying to use IBOutlets. :) IBOutlets are not loaded before initWithCoder:. You'll need to trap awakeFromNib instead.

From Apple's docs:

The nib-loading infrastructure sends an awakeFromNib message to each object recreated from a nib archive, but only after all the objects in the archive have been loaded and initialized. When an object receives an awakeFromNib message, it is guaranteed to have all its outlet and action connections already established.

You'd do so like this:

- (void)awakeFromNib
{
    [super awakeFromNib];
    for (UIView *circle in self.circles) {
        circle.layer.cornerRadius = circle.bounds.size.width / 2;
    }
}


来源:https://stackoverflow.com/questions/19823944/why-can-i-not-manipulate-the-objects-in-my-xib-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!