效果图
功能分析
freeform UIView in Empty XIB
ViewController
定义常量
//屏幕的高
#define kScreenH [UIScreen mainScreen].bounds.size.height
//屏幕的宽
#define kScreenW [UIScreen mainScreen].bounds.size.width
//应用界面的高
#define kAppViewH [JKAppView appView].bounds.size.height
//应用界面的宽
#define kAppViewW [JKAppView appView].bounds.size.width
//每行的个数
#define kTotalCol 3
加载plist中的数据
- (NSArray *)appViews{
if (!_appViews) {
NSString *path = [[NSBundle mainBundle]pathForResource:@"app" ofType:@"plist"];
NSArray *array = [NSArray arrayWithContentsOfFile:path];
NSMutableArray *arrayM = [NSMutableArray arrayWithCapacity:array.count];
for (NSDictionary *dict in array) {
JKAppInfo *appInfo = [JKAppInfo appInfoWithDict:dict];
JKAppView *appView = [JKAppView appView];
appView.appInfo = appInfo;
appView.delegate = self;
[arrayM addObject:appView];
}
_appViews = [arrayM copy];
}
return _appViews;
}
列间距计算
CGFloat margin = (kScreenW - kTotalCol * kAppViewW)/(kTotalCol + 1);
九宫格加载视图
//遍历应用界面数组
for (int i = 0 ; i<self.appViews.count; i++) {
//根据索引值取出单个应用界面
JKAppView *appView = self.appViews[i];
//九宫格的算法创建每个应用界面
int col = i % kTotalCol;
int row = i / kTotalCol;
CGFloat centerX = (margin + kAppViewW * 0.5) +(margin + kAppViewW) *col;
CGFloat centerY = (margin + kAppViewH * 0.5) +(margin + kAppViewH) *row;
appView.center = CGPointMake(centerX, centerY);
//加入到主视图中
[self.view addSubview:appView];
}
根据点击的按钮获得相关视图
JKAppView *appView = (JKAppView*)btn.superview;
菊花的frame值设定
juhua.frame = self.view.bounds;
菊花与”正在下载”标签
因为”正在下载”标签是添加在菊花上的,所以当菊花停止时,标签也会自动消失
标签逐渐消失 - 使用alpha
其效果为隐式动画,重新设定alpha值
noteLabel.alpha = 1;
[self.view addSubview:noteLabel];
[UIView animateWithDuration:5.0 animations:^{
noteLabel.alpha = 0;
} completion:^(BOOL finished) {
.....
}];
标签消失后
[UIView animateWithDuration:5.0 animations:^{
noteLabel.alpha = 0;
} completion:^(BOOL finished) {
btn.enabled = NO;
[btn setTitle:@"已下载" forState:UIControlStateDisabled];
[noteLabel removeFromSuperview];
}];
JKAppInfo
字典加载数据模型
属性名需要和plist中的字典key一一对应
- (instancetype)initWithDict:(NSDictionary *)dict{
if (self=[super init]) {
[self setValuesForKeysWithDictionary:dict];
}
return self;
}
创建image图像
- (UIImage *)image{
if (!_image) {
_image = [UIImage imageNamed:self.icon];
}
return _image ;
}
JKAppView
协议方法-点击下载按钮
@protocol JKAppViewDelegate <NSObject>
@optional
-(void)downloadClickWithBtn:(UIButton*)btn;
@end
@interface JKAppView : UIView
@property (nonatomic,weak) id<JKAppViewDelegate> delegate;
- 类与类之间的通讯,有三种方法:代理,通知,block
- 协议就好像一个武器,类本身不能使用,于是叫他的小弟”id
delegate” ,交由他人(viewController)使用
调用代理执行
- (IBAction)downloadBtnOnClick:(UIButton *)sender {
if ([self.delegate respondsToSelector:@selector(downloadClickWithBtn:)]) {
[self.delegate downloadClickWithBtn:sender];
}
}
UIView中加载XIB视图
UIView子类 + (Freeform View in Empty XIB)
+ (instancetype)appView{
//因为只有一个object,所以first or last都可以
return [[[NSBundle mainBundle]loadNibNamed:@"JKAppView" owner:nil options:nil]lastObject];
}