通过xib实现分页功能的封装

1、首先实现xib

UIView 的尺寸为300*130,因为准备的图片为600*260。

scrollView属性设置如下:

2、新建一个和xib同名的类

  2.1 类方法,返回xib对象

 + (instancetype)pageScroll
{
// NSStringFromClass 将类名转换成字符串,xib文件名和类名一样
return [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self) owner:nil options:nil] lastObject];
}

  2.2 添加一个属性保存图片名称

  @property (strong, nonatomic) NSArray *imageNames; // 图片名称

  然后 重写set方法

 - (void)setImageNames:(NSArray *)imageNames
{
_imageNames = imageNames; // 添加图片
for (int i = ; i < imageNames.count; i ++ )
{
UIImageView *imageView = [[UIImageView alloc] init];
imageView.image = [UIImage imageNamed:_imageNames[i]];
[self.scrollView addSubview:imageView];
}
// 设置pageControl的页数
self.pageControl.numberOfPages = _imageNames.count;
// 设置scrollView是否在滚动到中间是自动滑向出现较多的那个页面
self.scrollView.pagingEnabled = YES;
}

  2.3、计算每个控件的frame

 // layout ,计算控件的frame
- (void)layoutSubviews
{
[super layoutSubviews]; // 设置scrollView的frame
self.scrollView.frame = self.bounds;
//view的高度和宽度
CGFloat viewW = self.scrollView.frame.size.width;
CGFloat viewH = self.scrollView.frame.size.height; // view 的位置
self.scrollView.contentSize = CGSizeMake(viewW * _imageNames.count, );
// pageControl 的frame
self.pageControl.frame = CGRectMake(viewW - , viewH - , , ); // 计算图片的 frame
for(int i = ; i < _imageNames.count ; i ++)
{
UIImageView *imageView = self.scrollView.subviews[i];
imageView.frame = CGRectMake(i * viewW, , viewW, viewH);
}
}

  2.4、设置pageControl的当前滚动页

 // 代理方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
// 设置当前页的索引
self.pageControl.currentPage = (int)(scrollView.contentOffset.x / scrollView.frame.size.width + 0.5);
}

3、在控制器中加载xib文件

 - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib. // 加载ScrollView对象
SLQPageScroll *scroll = [SLQPageScroll pageScroll];
scroll.frame = CGRectMake(, , , );
scroll.imageNames = @[@"img_00",@"img_01",@"img_02",@"img_03"]; scroll.backgroundColor = [UIColor redColor];
[self.view addSubview:scroll]; }

最新文章

  1. 手把手教你在Ubuntu上安装Apache、MySql和PHP
  2. sublime简要笔记
  3. hdu 4006 The kth great number (优先队列)
  4. PHP的错误报错级别设置原理简析
  5. DNS:www.flickr.com
  6. Codeforces Round #279 (Div. 2) C. Hacking Cypher 前缀+后缀
  7. mysql 复杂的查询语句,工作中用到的记录下
  8. Bootstrap学习之路(3)---列表组件
  9. WebSorcket学习
  10. 基于spark的plsa实现
  11. Visual Studio之Nuget
  12. 函数(swift)
  13. Java集合框架学习(一)List
  14. 彻底搞懂 C# 的 async/await
  15. django 问题总结
  16. spring的第一天
  17. [转]How to Improve Entity Framework Add Performance?
  18. webui-popover 一个轻量级的jquery弹出层插件
  19. 【Python】【unittest】unittest测试框架中setup,teardown与setupclass,teardownclass的区别
  20. 2018/03/20 每日一个Linux命令 之 cp

热门文章

  1. windows xp professional 序列号(密钥)及百度网盘下载地址
  2. [Asp.Net] Global.asax
  3. 二叉搜索树(BST)学习笔记
  4. 使用canvas给图片添加水印
  5. SCSI add-single-device and remove-single-device
  6. Repeater控件里面取不到CheckBox的值
  7. SQLyog点击“测试连接”后,报2058错误
  8. Oracle 数字处理函数
  9. oc block排序
  10. 基于 muse-ui 封装一个微信公众号上传插件 实现多图上传