使用在storyBoard之外的xib创建对象

1、在storyBoard之外的xib
要注意的是:TableView的代理一定要设置为FilesOwner
使用:
方式一:
直接创建对象如下,(如果要使用xib里的控件,那么就要将xib里的控件作为成员变量了)
GACityRegonController *gaRegonVC=[[GACityRegonController alloc]init];
 
 
注意在storyBoard中,使用storyBoard获取对象的:
如:
GAViewController *vc= [self.storyboard instantiateViewControllerWithIdentifier:@"GAViewController"];
 
 
方式二:
从编译好的文件中获取(NSBundle中)
可以定义自己的类方法
//———————————ConstomUIView.h-----------------------------------------------
1、创建、并设置好xib
 
#import <UIKit/UIKit.h>
 
@interface ConstomUIView : UIView
//将xib的控件都作为属性
@property (unsafe_unretained, nonatomic) IBOutlet UIButton *imageButton;
@property (weak, nonatomic) IBOutlet UILabel *upLable;
@property (weak, nonatomic) IBOutlet UILabel *title;
//定义一个类方法,返回类对象
+(id)view;
@end
 
2、实现方法
//———————————ConstomUIView.m-----------------------------------------------
#import "ConstomUIView.h"
@implementation ConstomUIView

+(id)view{
    //从NSBundle中获取文件,创建类对象 
    return [[[NSBundle mainBundle]loadNibNamed:@"ConstomView" owner:nil options:nil] lastObject];
}
//防止横屏控件拉伸
- (id)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
//不自动设置大小
        self.autoresizingMask = UIViewAutoresizingNone;
    }
    return self;
}
@end
 
3、使用:调用类方法创建对象
ConstomUIView *cityView=[ConstomUIView view];
 
 
//---------------------------------------------------------------------
 
 
 
原文地址:https://www.cnblogs.com/lignpeng/p/5444740.html