XIB / Story Board / OC纯代码 创建(alloc)+初始化(init)

本文介绍了iOS中视图的几种加载方式,包括使用XIB文件加载、纯代码初始化及Storyboard加载,并展示了如何通过不同方法创建和配置UIView及UIViewController实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.View:

XIB:

+ (instancetype)loadFromNib {
    NSString *myclass = NSStringFromClass([self class]);
    // 封装Xib的加载过程
    return [[NSBundle mainBundle] loadNibNamed:myclass owner:nil options:nil].firstObject;
}
- (void)awakeFromNib {
    [super awakeFromNib];
    // add Initialization code
}
//调用
[xxx loadFromNib];

OC纯代码:

-(id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        //add init code
    return self;
}
//调用
[[xxx alloc] initWithFrame:...];

2.NSObject

OC纯代码:

- (instancetype)initWithxxx:(xxx)xxx  {
    self = [super init];
    if (self) {
        //add init code;
    }
    return self;
}
//调用
[[xxx alloc] initWithxxx:...];
//单例
+ (instancetype)sharedInstance {
    static ClassName *className;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        className = [[ClassName alloc] init];
    });
    return className;
}
//如果作为父类
+ (instancetype)sharedInstance {
    id instance = objc_getAssociatedObject(self, @"instance");
    if (!instance) {
        instance = [[super allocWithZone:NULL] init];
        objc_setAssociatedObject(self, @"instance", instance, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return instance;
}
//调用
[xxx sharedInstance];

3.ViewController

Story Board:

<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:<#@"Nib name"#> bundle:nil];
// Pass the selected object to the new view controller.
// Push the view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值