11.1UIScrollView

importUIKit

classViewController:UIViewController{

varpageControl:UIPageControl?

overridefuncviewDidLoad() {

super.viewDidLoad()

//屏幕的宽高

letwidth =view.frame.size.width

letheight =view.frame.size.height

//使用UIView的创建放过创建一个滑动视图

letscrollView =UIScrollView(frame:CGRectMake(0,0,width,height))

//背景颜色

scrollView.backgroundColor=UIColor.yellowColor()

//添加scrollView到屏幕上

view.addSubview(scrollView)

//设置滑动视图的滚动区域:contentSize

//只有contentsize大于scrollview本事的大小才可以滑动

scrollView.contentSize=CGSizeMake(7*width,0)

//设置UIScrollView的滚动范围之后,接下来用for循环的方式在scrollView平铺7张图片,注意每个imageView的位置

foriin1..<8{

letimageName ="h\(i).jpeg"

letimage =UIImage(named: imageName)

letimageView =UIImageView(frame:CGRectMake(CGFloat(i-1)*width,0, width, height))

//设置imageView显示的图片

imageView.image= image

scrollView.addSubview(imageView)

//设置当前位置的偏移量

scrollView.contentOffset=CGPointMake(width,0)

//设置是否整屏翻转

scrollView.pagingEnabled=true

//关闭水平滑动条

scrollView.showsHorizontalScrollIndicator=false

//关闭边界的回弹效果

scrollView.bounces=false

//代理(监听整个滑动过程)-协议(提供了整个过程的方法)

scrollView.delegate=self

//创建页面指示器(UIPageControl)

pageControl=UIPageControl(frame:CGRectMake(150,400,90,20))

//设置总共几个点(页面指示器有几个)

pageControl!.numberOfPages=7

view.addSubview(pageControl!)

//设置当前显示的点

pageControl!.currentPage=1

pageControl!.pageIndicatorTintColor=UIColor.redColor()

pageControl!.currentPageIndicatorTintColor=UIColor.greenColor()

view.addSubview(pageControl!)

}

}

overridefuncdidReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

}

}

/*遵守协议实现协议的方法*/

extensionViewController:

UIScrollViewDelegate{

funcscrollViewDidScroll(scrollView:UIScrollView) {

println("x =\(scrollView.contentOffset.x),y =\(scrollView.contentOffset.y)")

}

//滑动停止的时候调用

funcscrollViewDidEndDecelerating(scrollView:UIScrollView) {

letscrollViewWidth = scrollView.frame.size.width

letnum = scrollView.contentOffset.x/scrollViewWidth +1

pageControl?.currentPage=Int(num)

print("\(num)")

/*

//屏幕的宽高

let width = view.frame.size.width

let height = view.frame.size.height

print("x = \((scrollView.contentOffset.x)/(width)+1),0")

*/

}

}

你可能感兴趣的:(11.1UIScrollView)