1.oc版
+ (instancetype)viewFromXib { NSBundle* bundle = [NSBundle mainBundle]; NSString* className = NSStringFromClass([self class]); return [[bundle loadNibNamed:className owner:nil options:nil] objectAtIndexSafe:0]; }
使用:
CustomView* view = [CustomView viewFromXib];
2.swift版
static func newInstance() -> LeftView? { let objc = Bundle.main.loadNibNamed("LeftView", owner: nil, options: nil) if let view = objc?.first as? LeftView { return view } return nil }
使用:
let view = CustomView.newInstance()!
本文介绍了如何在Objective-C及Swift中从XIB文件加载自定义视图的方法。通过使用NSBundle加载对应类名的XIB文件,可以方便地实例化视图对象。此方法适用于希望分离视图布局与代码逻辑的开发者。
6万+

被折叠的 条评论
为什么被折叠?



