iOS 跨多个 UIViewController 从 Nib 文件实例化自定义 View

标签 ios xib custom-view

我需要一个如何从 nib 文件实例化自定义 View 的示例。我把头绕在几个stackoverflow帖子上,但我没有明白。也许我只需要一个提示如何去做。

我想要做的是 - 使用界面构建器创建自定义 View 。它应该是一个模板,以便我可以多次实例化它以将其添加到多个 View Controller 。

到目前为止,我已经创建了名为 MyIssueView.xib 的自定义 View xib 文件。它实际上只包含主视图和一些标签。

我在 MyIssueView.xib 中为我的标签创建了一个名为 IssueView 的 UIView 子类。

我现在如何将网点与 IB 连接起来?以及如何从任何 ViewController 实例化 IssueView?

很高兴举个例子!
干杯。

更新:

我现在有

问题 View .xib
IssueView.h(UIView 子类)
问题 View .m

我的问题 View .h:

#import <UIKit/UIKit.h>

@interface IssueView : UIView

@property (weak, nonatomic) IBOutlet UILabel *label1;
@property (weak, nonatomic) IBOutlet UILabel *label2;
@property (weak, nonatomic) IBOutlet UILabel *label3;
@property (weak, nonatomic) IBOutlet UILabel *label4;

@end

我的问题 View .m:
#import "IssueView.h"

@implementation IssueView
@end

我的 ViewController.m:
#import "AllIssuesViewController1.h"
#import "IssueView.h"
#import "UIView+NibLoading.h"

@interface AllIssuesViewController1 ()

@end

@implementation AllIssuesViewController1


- (void) loadView
{

}

- (void)viewDidLoad
{
    [super viewDidLoad];

    _issueView = [IssueView loadInstanceFromNib];
}

它给了我一个错误:
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSObject 0x8292580> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key label1.'

最佳答案

我有一个扩展 UIView 的类别,称为 UIView+NibLoading。

在它是这个代码......

#import "UIView+NibLoading.h"

@implementation UIView (NibLoading)

+ (id)loadInstanceFromNib
{
    UIView *result;

    NSArray* elements = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:nil options:nil];

    for (id anObject in elements) {
        if ([anObject isKindOfClass:[self class]]) {
            result = anObject;
            break;
        }
    }

    return result;
}

@end

然后,当我想从 nib 实例化 UIView 子类时,我只需导入类别即可运行...
self.issueView = [IssueView loadInstanceFromNib];\

你需要像这样连接标签......

enter image description here

如果将标签连接到“文件所有者”,则需要删除这些连接。

关于iOS 跨多个 UIViewController 从 Nib 文件实例化自定义 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13560671/

相关文章:

ios - 引用架构 x86_64 : "_sqlite3_close", 的 undefined symbol

iphone - CGBitmapContextCreate 的内存使用率非常高

html - 如何仅使用 CSS 压缩应用程序图标图像

ios - 在从 xib 文件实例化的自定义 View 中将导出连接到约束导致崩溃

安卓上滑 View

ios - Create Circle Image View IOS问题

ios - 以编程方式为给定 iTunes ID 的所有地区构建 iTunes URL?

ios - 如何向自定义表格 View 单元格 xib 文件添加约束?

ios - 从 xib 创建 UITabBarController 时黑屏

android - 在 IDE 布局编辑器中检查方向