如何从xib实例化视图?

时间:2012-01-26 01:52:06

标签: objective-c

我在xib文件中有一个视图,我想将该视图放入窗口....我正在使用此代码:

- (void) popupNotificationWithTag:(NSString *)tag fade:(double)msFade lineOne:(NSString *)lineOneText lineTwo:(NSString *)lineTwoText
{
    NotificationWindow *notificationWindow;
    NotificationWindow *tmpWindow;
    NSEnumerator *enumerator;

    // Walk the notification windows in the array
    enumerator = [self.notificationWindows objectEnumerator];
    if(enumerator)
    {
        while((tmpWindow = [enumerator nextObject]))
        {
            if([tmpWindow.tag isEqualToString:tag])
            {
                notificationWindow = tmpWindow;
            }
        }
    }

    // Make a new notification window
    if (!notificationWindow)
    {
        int width = [[NSScreen mainScreen] frame].size.width;
        int height = [[NSScreen mainScreen] frame].size.height;

        notificationWindow = [[NotificationWindow alloc] initWithRect:NSMakeRect(width - 420, height - 130, 400, 100)];
        NSNib *nib = [[NSNib alloc] initWithNibNamed:@"Notification" bundle: nil];
        NSArray *objects;
        [nib instantiateNibWithOwner:self topLevelObjects:&objects];
        [notificationWindow setContentView: [objects objectAtIndex:0]];

        [notificationWindow setTag:tag];         
        [self.notificationWindows addObject:notificationWindow];
    }

    // Display window
    [notificationWindow makeKeyAndOrderFront:nil];
    [notificationWindow display];
    notificationWindow.fadeOut = msFade;
    [notificationWindow setPrimaryText:lineOneText];
}

视图是xib文件中唯一的东西,所以虽然objectAtIndex:0会没问题,但我会在那一行得到-[NSApplication setFrame:]: unrecognized selector sent to instance 0x100508500异常。

更新我用这段代码替换了这行:

    for (id obj in objects) {
        if ([[obj class] isSubclassOfClass:[NSView class]])
            [notificationWindow setContentView: obj];
    }

1 个答案:

答案 0 :(得分:1)

我含糊地回忆起,笔尖有一个隐藏的第一个对象,代表第一个响应者(或其他东西)。尝试使用objectAtIndex:1,看看是否有效。