Monday, March 12, 2012

AQGridView, load AQGridCell from xib file

Recently I am working on an app , which will need to use AQGridView, which will allow me to present my content in a grid format.
Like the UITableView, we need to implement a class to draw the cell content, and this class should inherit from AQGridCell.  the downside of this method is , we need to draw the whole cell UI use code, if it is simple cell , that should be fine. but I don't want to write too much code which can be done with a xib file. so I was thinking how to load a xib file on the fly. it does take me sometime to figure it out, thus I write it down, hope someone else still want to do the same thing can benefit from this, also for myself , if later on I need to implement similar features, I can come back to read it, my long term memory is bad.

So here it is.
First of all, I create a class and inherit it from UIView,


#import <UIKit/UIKit.h>

@interface TVViewCellWithUI : UIView
{
    
}

Then I create a xib file call it , TVViewCellWithUI.xib, pretty simple , put one UIImagView and a couple labels on it, 
On the view, I set the view is "TVViewCellWithUI" 

Then I can create outlet, actions stuff with drag and drop in TVViewCellWithUI class. 


then , the tricky part is , how I create the AQGridCell ,  refer to the following snapshot. 


so what I did is , first of all I create an instance of TVViewCellWithUI and then use NSBundle to load the TVViewCellWithUI xib file dynamically.  after that , assign the first element of the array to TVViewCellWithUI instance.
TVViewCellWithUI *vClass = [[TVViewCellWithUI alloc] init];
        NSArray* array = [[NSBundle mainBundle] loadNibNamed:@"TVViewCellWithUI" owner:vClass options:nil];
        
        vClass = [array objectAtIndex:0];

Note, NSArray* array = [[NSBundle mainBundleloadNibNamed:@"TVViewCellWithUI" owner:vClass options:nil]; the type of owner parameter should match with the type of the root view which we specified in the xib file, in my cause it is TVViewCellWithUI. 

if a different type of instance has been passed in as the owner, you will get unexpected result, for me , the function will stuck there without return control to you. 

after all these , create an instance of AQGridViewCell , and also add the TVViewCellWithUI into 
filledCell = [[AQGridViewCell alloc] initWithFrame:vClass.frame reuseIdentifier:FilledCellIdentifier];
        [filledCell.contentView addSubview:vClass];

In this way, we can take advantage of the xib file which we can easily change the UI without writing extra code.



1 comment: