在工作的过程中发现Xcode8无法创建带.h和.m文件对的xib 因为xib布局简单 所以我决定还是采用xib 我直接创建了一个xib然后创建了一个文件对进行关联 在实际操作过程中还是有一些小问题 比如view中的控件调用 现将主体代码附上 有什么疑问可以询问
YellowView.h/m
@interface YellowView : UIView
+ (instancetype)viewFromNIB;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@end
@implementation YellowView
// Convenience Method
+ (instancetype)viewFromNIB {
// 加载xib中的视图,其中xib文件名和本类类名必须一致
// 这个xib文件的File's Owner必须为空
// 这个xib文件必须只拥有一个视图,并且该视图的class为本类
NSArray *views = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:nil options:nil];
return views[0];
}
- (void)awakeFromNib {
// 视图内容布局
self.backgroundColor = [UIColor yellowColor];
self.titleLabel.textColor = [UIColor whiteColor];
}
@end
MainViewController.m
...
@property (strong, nonatomic) YellowView *yellowView;
...
- (void)loadYellowViewFromXIB {
// 说明见YellowView.m的viewFromNIB方法
self.yellowView = [YellowView viewFromNIB];
CGRect rect = _yellowView.frame;
UIView *redView = _redViewOwner.redView;
rect.origin.x = redView.frame.origin.x;
rect.origin.y = redView.frame.origin.y + 80.0f;
_yellowView.frame = rect;
[self.view addSubview:_yellowView];
}