iOS 使用nib文件(一)

首先是加载nib文件的方法:

- (NSArray *)loadNibNamed:(NSString *)name owner:(id)owner options:(NSDictionary *)options;

Return Value

An array containing the top-level objects in the nib file. The array does not contain references to the File’s Owner or any proxy objects; it contains only those objects that were instantiated when the nib file was unarchived. You should retain either the returned array or the objects it contains manually to prevent the nib file objects from being released prematurely. 

Discussion

You can use this method to load user interfaces and make the objects available to your code. During the loading process, this method unarchives each object, initializes it, sets its properties to their configured values, and reestablishes any connections to other objects. (To establish outlet connections, this method uses the setValue:forKey: method, which may cause the object in the outlet to be retained automatically.) For detailed information about the nib-loading process, see Resource Programming Guide.

该方法的返回值是一个数组,数组不包含对File‘s Owner或者任何代理对象的引用,仅仅包含了nib文件在unarchived时被初始化的对象。你应该retain这个数组或者数组中对象以避免对象被提前释放。

你可以使用该方法来加载UI,并使UI中包含的对象在你的代码中是可用的。在加载过程中,该方法unarchived每一个对象,初始化、设置属性被计算出来的值,同时重新建立和其他对象建立的connections。为了建立outlet connections,该方法使用了setValue:forKey:,可能会导致对象被自动retain.

nib文件就是存储了归档对象数据的文件,通过对该类型文件进行解档,我们可以恢复被归档的对象。

#import 

@interface TestNibView : UIView

@property (weak, nonatomic) IBOutlet UIButton *button;
+(instancetype)testNibView;

@end

#import "TestNibView.h"

@implementation TestNibView

+(instancetype)testNibView
{
    return [[[NSBundle mainBundle]loadNibNamed:@"TestNibView" owner:self options:nil] firstObject];
}


-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        
    }
    return self;
}

-(id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self)
    {
        DLog(@"%@",self.button);
    }
    return self;
}

-(void)awakeFromNib
{
    [super awakeFromNib];
    DLog(@"%@",self.button);
}

@end
+(instancetype)testNibView;//只能使用代码创建
 
  

TestNibView.xib的内容如下图:

iOS 使用nib文件(一)_第1张图片

为什么这种方法只能通过代码创建,而不能像其他的控件一样,拖到其他的view上呢,下次再说。

上面这种方法在我们使用xib自定义cell,为cell关联自定类时最常用。

对于UITableViewCell和UICollectionViewCell,我们可以直接使用xib生成cell。

     
UIXXCell * cell  =  [[[NSBundle mainBundle]loadNibNamed:@"CellPractice" owner:self options:nil] firstObject];
 
  

- (NSArray *)loadNibNamed:(NSString *)name owner:(id)owner options:(NSDictionary *)options;中options参数在文档中也有说明,只是很少用到。

在TestNibView.m中还有几个方法,是下次要研究的内容。

你可能感兴趣的:(ios)