实现效果:
(1)点击按钮,更改显示的图片,描述和页码
(2)当显示第一张图片时,左按钮不能点击。最后一张时,右按钮不能点击(变灰)
掌握知识:
(1)学会获取plist资源。
(2)学会懒加载的使用。
效果如下:
实现思路:
(1)拖去相应的控件到界面,布局界面。
(2)拖线设置控件的属性和绑定按钮方法
(3)编写业务逻辑代码
首先我们设置好plist文件,plist文件作用是存放一定规则的数据。懂得java的同学应该知道,这家伙有点像xml文件,但是解析的时候比xml简单多了。
下面看看plist到底长出什么样子的。可以看出,这里存放的是数组,数组里面是Dictionary集合
话不多说,马上看看程序中的实现代码
ViewController.m
//
// ViewController.m
// 图片浏览器03-plist
//
// Created by zxh on 15/8/21.
// Copyright (c) 2015年 zxh. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
//页码
@property (weak, nonatomic) IBOutlet UILabel *noLable;
//显示图片
@property (weak, nonatomic) IBOutlet UIImageView *iconImage;
//描述
@property (weak, nonatomic) IBOutlet UILabel *descLable;
//左按钮
@property (weak, nonatomic) IBOutlet UIButton *leftBtn;
//右按钮
@property (weak, nonatomic) IBOutlet UIButton *rightBtn;
//存储资料数组
@property (strong,nonatomic) NSArray * array;
//下标
@property (assign,nonatomic) int index;
//上一张
- (IBAction)previous;
//下一张
- (IBAction)next;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.index = -1;
[self next];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/**
* array get 方法: 懒加载资源文件,并存储到数组中
*
* @return 图片数组
*/
-(NSArray *)array{
if (_array == nil) {
//初始化数据
//file:全路径
//NSBundle:一个NSBundle代表一个文件夹
//利用mianBundle就可以访问手机里面的任何资源
NSBundle *bundle = [NSBundle mainBundle];
//获取imageData.plist的全路径
NSString *path = [bundle pathForResource:@"imageData" ofType:@"plist"];
//图片自由存储到数组中
_array = [NSArray arrayWithContentsOfFile:path];
}
return _array;
}
/**
* 改变显示的方法
*/
-(void) changeData{
//1.设置标题
self.noLable.text = [NSString stringWithFormat:@"%d/%lu",self.index,self.array.count];
//2.获取存储到数组中的数据
NSMutableDictionary *imagedic = self.array[self.index];
//3.设置图片
self.iconImage.image = [UIImage imageNamed:imagedic[@"icon"]];
//4.设置描述
self.descLable.text = imagedic[@"desc"];
//5.设置按钮状态
self.leftBtn.enabled = (self.index!=0);
self.rightBtn.enabled = (self.index != self.array.count-1);
}
/**
* 上一张
*/
- (IBAction)previous {
self.index --;
[self changeData];
}
/**
* 下一张
*/
- (IBAction)next {
self.index ++;
[self changeData];
}
@end
备注:
1.何为懒加载?
懒加载(在java中又称懒汉式),意思是没有用到时不会去加载资源(执行代码),用到的时候才去加载。 与懒加载对立的是饥汉式,饥汉式是程序启动的时候就去加载资源(执行代码)。
2. 查找模拟器手机安装app 的imageData.plis文件在什么地方?
可参考文章:找不到iphone simulator?
好久都找不到,目录太深了,最好的办法就是代码打印出来。我的xcode是6.4,路径如下:
/Users/username/Library/Developer/CoreSimulator/Devices/833F498A-D2E2-4E30-BD6C-E656056080EB/data/Containers/Bundle/Application/504E2C80-8C88-48D8-9FD9-D5EEB64A8A84/图片浏览器03-plist.app/imageData.plist
username是你的用户名,找到图片浏览器03-plist.app点击显示包内容,即可看到app里面的资源文件。
----------------------文章至此!