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