Swift - 使用UIScrollView实现页面滚动切换

UIScrollView提供了以页面为单位滚动显示各个子页面内容的功能,每次手指滑动后会滚动一屏的内容。

要实现该功能,需要如下操作:

1,将UIScrollView的pagingEnabled属性设置成true

2,必须通过contentSize属性设置各个页面相加的宽度。比如iphone手机一屏宽度是320,如果有3个页面,则contentSize就需要设置为320*3=960

3,最好将showsHorizontalScrollIndicator和showsVerticalScrollIndicator设置成false隐藏横向和纵向滚动条。

4,如果scrollsToTop不需要也设置成false。

--- 主页面 ---

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

classViewController:UIViewController{

letnumOfPages = 3

letpageWidth = 320

letpageHeight = 360

overridefuncviewDidLoad(){

super.viewDidLoad()

//scrollView的初始化

varscrollView =UIScrollView()

scrollView.frame =self.view.bounds

//为了让内容横向滚动,设置横向内容宽度为3个页面的宽度总和

scrollView.contenSize=CGSizeMake(CGFloat(pageWidth*numOfPages),CGFloat(pageHeight))

scrollView.pagingEnabled =true

scrollView.showsHorizontalScrollIndicator =false

scrollView.showsVerticalScrollIndicator =false

scrollView.scrollsToTop =false

//添加子页面

foriin0..numOfPages{

varmyViewController =MyViewController(number:(i+1))

myViewController.view.frame =CGRectMake(CGFloat(pageWidth*i),

CGFloat(0),CGFloat(pageWidth),CGFloat(pageHeight))

scrollView.addSubview(myViewController.view)

}

self.view.addSubview(scrollView)

}

}

--- 子页面 ---

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

classMyViewController:UIViewController{

varnumber:Int!

letcolorMap=[

1:UIColor.blackColor(),

2:UIColor.orangeColor(),

3:UIColor.blueColor()

]

init(number initNumber:Int){

self.number = initNumer

super.init(nibNmae:nil, bundle:nil)

}

overridefuncviewDidLoad(){

varnumberLabel =UILabel(frame:CGRectMake(0,0,100,100))

numberLabel.center =self.view.center

numberLabel.text ="第\(number)页"

numberLabel.textColor =UIColor.whiteColor()

self.view.addSubview(numberLabel)

self.view.backgroundColor = colorMap[number]

}

}