objective-c - 在没有 View Controller 的情况下使用 xib

标签 objective-c ios cocoa-touch xib

我需要创建几个类似的 View
以一种简单的方式,我在 xib 中创建了一些 View (每个全屏)

我有一个 View Controller 来使用这个 xib 的 View ,代码如下:

NSArray* views = [[NSBundle mainBundle] loadNibNamed:@"MyXibName" owner:nil options:nil];
[self.view addSubview:[views objectAtIndex:aIndex]];

此时 View 显示正常。

现在,这些 View 中有一些按钮,所以我为每个 View 连接一个 socket

坏事发生了

应用程序因以下原因崩溃

uncaught exception 'NSUnknownKeyException', reason: '[<NSObject 0x969db50> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key

分析:
虽然我的xib文件的“文件所有者”已经设置,但是xib和唯一的 View Controller 之间没有连接。

如何获取 View 按钮的指针?

最佳答案

你可以这样做:

NSNib*      aNib = [[NSNib alloc] initWithNibNamed:@"MyGreatNib" bundle:nil];
NSArray*    topLevelObjs = nil;

for (SomeClass *obj in myOwnerObjects) {
    topLevelObjs = nil;

    if (![aNib instantiateNibWithOwner:obj topLevelObjects:&topLevelObjs])
    {
        NSLog(@"Warning! Could not load nib file.\n");
        return;
    }

    for (id topLevelObj in topLevelObjs) {
        if ([topLevelObj isKindOfClass:[NSView class]]) {
            NSView *otView = (NSView *)topLevelObj;
            // set frame...
            [self addSubview:otView];
        }
    }
}   

关于objective-c - 在没有 View Controller 的情况下使用 xib,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12157689/

相关文章:

iphone - 有没有办法永久保存游戏数据?

iOS:在调用 reloadRowsAtIndexPaths 时,didEndDisplayingCell 被调用两次

iphone - NSArray for 循环枚举顺序是否有保证?

ios - 如何查询具有特定属性值的核心数据对象

ios - 如何做文本字段抖动效果?

ios - 通过 UILocal 通知打开特定的 url,而不是打开应用程序

iphone - 如何创建像UITableViewCell这样的TextField?

iphone - 适用于 iphone 的 Mapsforge 模拟

ios - 作为 SubView VS ChildViewController 查看

objective-c - IOS UITableViewCell Spacer(或边距)