创建一个通过点击按钮,切换不同图片的图片浏览器。
1.首先创建一个plist文件,用于存储不同图片,以及不同图片的标题。
2.程序运行要加载这个plist文件保存在一个dict中,
3.通过按钮访问这个dict中的不同图片。
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic,strong) NSArray *pic;
@property (nonatomic,assign) int index;//记录索引
- (IBAction)next;//下一张按钮动作
@property (weak, nonatomic) IBOutlet UILabel *lblindex;//第几张图片显示
@property (weak, nonatomic) IBOutlet UIImageView *imageviewicon;//图片
@property (weak, nonatomic) IBOutlet UILabel *lbltitle;//标题
@property (weak, nonatomic) IBOutlet UIButton *nextbutton;//控制下一张按钮状态
- (IBAction)pre;//上一张按钮动作
@property (weak, nonatomic) IBOutlet UIButton *prebutton;//控制下一张按钮状态
@end
@implementation ViewController
//懒加载,用的时候才加载,加载图片列表
-(NSArray *) pic{
if(_pic==nil){
NSString *path = [[NSBundle mainBundle] pathForResource:@"pic.plist" ofType:nil]; //读取目录
NSArray *array = [NSArray arrayWithContentsOfFile:path];//根据目录读取队列
_pic = array;
}
return _pic;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.index = -1;//因为是懒加载,所以程序刚开始运行并不会访问plist列表,而是显示最初的,因此要为-1,再自动运行一次,直接到index=0时访问plist。
[self next];
}
- (IBAction)next {
self.index++;
[self setdata];
}
- (IBAction)pre {
self.index--;
[self setdata];
}
//封装
-(void) setdata{
//获取图片
NSDictionary *dict = self.pic[self.index];
//显示当前是第几张
self.lblindex.text = [NSString stringWithFormat:@"%d/%ld",self.index+1,self.pic.count];//因为创建的时候就是第一张,当已经点击的时候,就要显示第二张了。
//设置图片
self.imageviewicon.image = [UIImage imageNamed:dict[@"icon"]];
//设置标题
self.lbltitle.text =dict[@"title"];
//按钮是否可以点击,最后和第一个时防止数组越界
if(self.index==0){
self.prebutton.enabled = NO;
}
else{
self.prebutton.enabled = YES;
}
if(self.index==self.pic.count-1){
self.nextbutton.enabled = NO;
}
else{
self.nextbutton.enabled = YES;
}
}
@end