实际编程过程中很多View需要复用以便减轻工作量提高效率。本文以嵌套UISCrollView的UIView作为例子,简单讲述自定义UIView的过程。
示例代码下载:https://github.com/eliyar917/Swift-CustomUIScrollView
基本创建 创建UIView 选择添加新文件 -> Cocoa Touch Class -> Subclass选择UIView -> 创建
创建后文件内容如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 import UIKitclass SampleScrollView : UIView { }
初始化 按照Swift自定义初始化(待更新)中所使用方式添加初始化函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 private var array:NSMutableArray !private var scrollView:UIScrollView !override init (frame : CGRect ) { super .init (frame: frame) } required init (coder aDecoder : NSCoder ) { super .init (coder: NSCoder ()) } convenience init (inView : UIView ,array :NSMutableArray ) { let rect = CGRect (x: 0 , y: 0 , width: inView.frame.width, height: inView.frame.height) self .init (frame: rect) self .array = array setUI() }
初始化ScrollView并添加到该UIView种
1 2 3 4 5 6 7 8 9 10 11 12 13 14 func setUI () { scrollView = UIScrollView (frame: CGRectMake (0 , 0 , self .frame.width, self .frame.height)) self .addSubview(scrollView) scrollView.tag == 10 scrollView.bounces = true scrollView.alwaysBounceHorizontal = true scrollView.pagingEnabled = true scrollView.showsHorizontalScrollIndicator = false scrollView.scrollsToTop = true scrollView.showsVerticalScrollIndicator = false scrollView.contentSize = CGSizeMake (self .frame.width * CGFloat (array.count), self .frame.height) scrollView.scrollRectToVisible(CGRectMake (0 , 0 , self .frame.width, self .frame.height), animated:false ) }
设置内容 填充ScrollView内容,遍历array,添加图片到UIView,每个图片为一页,初始化setUI()
后调用
1 2 3 4 5 6 7 8 9 func addContent () { var x = CGFloat (0 ) for i in array { let imageView = UIImageView (frame: CGRectMake (x, 0 , self .frame.width, self .frame.height)) imageView.image = UIImage (named: "\(i) " ) self .scrollView.addSubview(imageView) x += self .frame.width } }
监管滑动 利用UIScrollViewDelegate来监管滑动并Log中打印出滑动页数。 首先修改class SampleScrollView:UIView
这一部分,添加UIScrollViewDelegate
1 class SampleScrollView : UIView ,UIScrollViewDelegate
设置Delegate对象,在setUI()
函数中增加下面一行
1 scrollView.delegate = self
调用scrollViewDidEndDecelerating
,监管滑动并Log中打印出滑动页数
1 2 3 4 5 func scrollViewDidEndDecelerating (scrollView : UIScrollView ) { let pageWidth:CGFloat = scrollView.frame.size.width; let page:Int = Int (scrollView.contentOffset.x / pageWidth) println(page) }
进阶 自定义开始页数 添加函数
1 2 3 func startFromPage (page :Int ) { scrollView.scrollRectToVisible(CGRectMake (self .frame.width * CGFloat (page), 0 , self .frame.width, self .frame.height), animated:false ) }
创建完SampleScrollView,可以设置从第几页开始展示
调用 1 2 3 var scroller = SampleScrollView (inView: self .view, array: array)scroller.startFromPage(3 ) self .view.addSubview(scrollr)