我創建了MyCustomView.xib/h/m:它擴展了UIView
類。然後在我的Main.storyboard中,放入UIView
對象,將類更改爲MyCustomView並鏈接到MainController.h。所以,MainController包含對MyCustomView實例的引用。 對於從廈門國際銀行加載,在MyCustomView我做到以下幾點:委託正在發佈的情況下自定義查看使用XIB創建
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
if (self.subviews.count == 0) {
[self commonInit];
}
}
return self;
}
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self commonInit];
}
return self;
}
- (void) stretchToSuperView:(UIView*)view
{
view.translatesAutoresizingMaskIntoConstraints = NO;
NSDictionary *bindings = NSDictionaryOfVariableBindings(view);
NSString *formatTemplate = @"%@:|[view]|";
for (NSString * axis in @[@"H",@"V"]) {
NSString * format = [NSString stringWithFormat:formatTemplate,axis];
NSArray * constraints = [NSLayoutConstraint constraintsWithVisualFormat:format options:0 metrics:nil views:bindings];
[view.superview addConstraints:constraints];
}
}
- (void)commonInit
{
MyCustomView* view = nil;
NSArray *views = [[NSBundle mainBundle] loadNibNamed:@"MyCustomView" owner:self options:nil];
view = views.firstObject;
[self addSubview:view];
[self stretchToSuperView:views.firstObject];
}
這工作得很好,直到我想,以通知MainController任何變化(點擊按鈕等)申報委託在MyCustomView。所以,我的ManController符合MyCustomViewDelegate
並實現方法。
編輯1個設置委託
//MainViewController.m file
@interface MainViewController()
@property (strong, nonatomic) IBOutlet MyCustomView *customView;
@end
@implementation MainViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.customView.delegate = self;
}
這裏的問題是,委託變成零,我不明白其中的道理,所以不知道什麼是錯誤的。
編輯2我覺得我有2個不同的MyCustomView實例。 我在MyCustomView增加新的屬性:
@interface MyCustomView : UIView
@property (weak, nonatomic) IBOutlet UIButton *firstItem;
@property(nonatomic, weak)id <MyCustomViewDelegate> delegate;
// this is test property
@property(nonatomic, assign)int testProperty;
@end
當我在viewDidLoad中設置該屬性,然後點擊第一個按鈕,我看到testProperty具有值0,所以,這可能意味着一些錯誤IBOutlet中MyCustomView * customView。
@Rob是的,代表很弱。 ViewController不能被釋放,因爲它是前端控制器,它實際上是我的實驗項目中的單個控制器。 – someUser
customView不是零。我將Main.storyboard的MyCustomView鏈接到控制器。 – someUser