功能需求
实现一个图片浏览器,点击左右按钮可以切换背景图,且更新背景图对应的索引页和图片描述内容。
分析:
- 实现一个UIView的子类即可,该子类包含多个按钮。
实现步骤:
-
使用OC语言,故创建cocoa Touch类型文件。Xcode会创建.h文件和.m文件:PicBrowserDemo类。
-
图片资源导入:注意图片不要重名
注意各项的类型:Root是Array,其余是Dictionary
-
实现该类。
该类带有多个控件,令其继承UIView。
a. 声明类的成员变量:在.h文件中定义:,类型是strong。
该图片浏览器需要两个可显示文字内容但不可修改的Label、两个前后图片切换的按钮以及承载图片的视图。
在.h 文件中:
@interface PicBrowserDemo : UIView
@property(strong, nonatomic) UIImageView *imageView;
@property(strong, nonatomic) UILabel *label1;
@property(strong, nonatomic) UILabel *label2;
@property(strong, nonatomic) UIButton *btn1;
@property(strong, nonatomic) UIButton *btn2;
@end
b. 创建plist类型文件,直接在项目下创建,plist文件属于resource类型文件,在该栏目下可找到。
选择root类型为Array,而每个元素设置为字典,因为每个字典中存图片的名称和title(描述)。
c. .m 文件:
// 1 plist:
信息填写
// 2 初始化各个组件,显示的信息以第一张为基准
// 3 nxt
// 4 pre
// 5 降低冗余,合并:pre、nxt函数
#import "PicBrowserDemo.h"
// 写私有属性:在这里
@interface PicBrowserDemo()
// assign、strong的区别: asign表示基本类型的变量
@property(nonatomic, strong) NSArray *pic;
@property(nonatomic, assign) int index;
@end
// 从plist中读取到的各图片信息集合
@implementation PicBrowserDemo
-(instancetype) initWithFrame:(CGRect)frame{
self = [super initWithFrame:frame];
if(self){
// 初始化5个组件
_imageView = [[UIImageView alloc] initWithFrame:CGRectMake(80, 230, 150, 150)];
// 图片模式:放入如何显示的 按比例缩放,不会拉伸变形
_imageView.contentMode = UIViewContentModeScaleAspectFit;
// 初始化为pic中第一张图片
NSDictionary *dict = self.pic[0];