24.小项目:应用市场 版本7.0
新建一个CZappView类,将其与Xib一一对应。
CZappView的实例对象,等同于Xib本身。
实例对象具备的属性,等同于Xib的子控件。
------------- CZapp.h -------------
#import <Foundation/Foundation.h>
@interface CZApp : NSObject
@property (nonatomic,copy) NSString *name;
@property (nonatomic,copy) NSString *icon;
- (instancetype) initWithDict:(NSDictionary *) dict;
+ (instancetype) appWithDict:(NSDictionary *) dict;
+ (NSArray *) apps;
@end
------------- CZapp.m -------------
#import "CZApp.h"
@implementation CZApp
- (instancetype)initWithDict:(NSDictionary *)dict
{
if (self = [super init]) {
self.name = dict[@"name"];
self.icon = dict[@"icon"];
}
return self;
}
+ (instancetype)appWithDict:(NSDictionary *)dict
{
return [[self alloc] initWithDict:dict];
}
+ (NSArray *) apps
{
NSString *path = [[NSBundle mainBundle] pathForResource:@"app" ofType:@"plist"];
NSArray *array = [NSArray arrayWithContentsOfFile:path];
NSMutableArray *arrayM = [NSMutableArray array];
for (NSDictionary *dict in array)
{
CZApp *app = [CZApp appWithDict:dict];
[arrayM addObject:app];
}
return arrayM;
}
@end
------------- CZappView.h -------------
#import <UIKit/UIKit.h>
#import "CZApp.h"
@interface CZAppView : UIView
@property (nonatomic,strong) CZApp *app;
@end
------------- CZappView.m -------------
#import "CZAppView.h"
@interface CZAppView ()
@property (weak, nonatomic) IBOutlet UIImageView *iconView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@end
@implementation CZAppView
- (void)setApp:(CZApp *)app
{
_app = app;
self.iconView.image = [UIImage imageNamed:app.icon];
self.nameLabel.text = app.name;
}
@end
------------- ViewController.m -------------
#import "ViewController.h"
#import "CZApp.h"
#import "CZAppView.h"
@interface ViewController ()
@property (nonatomic,strong) NSArray *apps;
@end
@implementation ViewController
- (NSArray *)apps
{
if(_apps == nil)
{
_apps = [CZApp apps];
}
return _apps;
}
- (void)viewDidLoad
{
[super viewDidLoad];
CGFloat appW = 100;
CGFloat appH = 100;
int numOfCol = 3;
CGFloat marginX = (self.view.frame.size.width - appW * numOfCol) / (numOfCol + 1);
CGFloat marginY = 20;
for (int index = 0; index < self.apps.count; index++)
{
CZAppView *appView = [[[NSBundle mainBundle] loadNibNamed:@"CZAppView" owner:nil options:nil] lastObject];
int col = index % numOfCol;
CGFloat appX = marginX + (appW + marginX) * col;
int row = index / numOfCol;
CGFloat appY = 20 + marginY + (appH + marginY) * row;
appView.frame = CGRectMake(appX, appY,appW,appH);
[self.view addSubview:appView];
CZApp *app = self.apps[index];
appView.app = app;
}
}
@end