![](/img/trans.png)
[英]How to instantiate a custom iOS UIViewController and use it's NIB under Storyboard?
[英]iOS Instantiate Custom View from Nib File across multiple UIViewController
我需要一個如何從nib文件實例化自定義視圖的示例。 我把頭纏在幾個stackoverflow帖子上,但我不明白。 也許我只需要提示如何做。
我想做的是-使用界面生成器創建自定義視圖。 它應該是一個模板,以便我可以實例化它多次以將其添加到多個視圖控制器。
到目前為止,我已經創建了名為MyIssueView.xib的自定義視圖xib文件。 實際上,它僅由主視圖和一些標簽組成。
然后,我在MyIssueView.xib中創建了一個名為IssueView的UIView子類,其中包含我的標簽的插座。
我現在如何與IB掛鈎呢? 以及如何從任何ViewController實例化IssueView?
舉個例子很高興! 干杯。
更新:
我現在有
IssueView.xib IssueView.h(UIView子類)IssueView.m
我的IssueView.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
我的IssueView.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
然后,當我想從筆尖實例化UIView子類時,只需導入類別即可運行...
self.issueView = [IssueView loadInstanceFromNib];\
您需要像這樣連接標簽...
如果將標簽連接到“文件的所有者”,則需要刪除這些連接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.