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
class ViewController : UIViewController {
let numOfPages = 3
pageWidth = 320
pageHeight = 360
override func viewDidLoad(){
super .viewDidLoad()
//scrollView的初始化
var scrollView = UIScrollView ()
scrollView.frame = self .view.bounds
//为了让内容横向滚动,设置横向内容宽度为3个页面的宽度总和
scrollView.contenSize= CGSizeMake ( CGFloat (pageWidth*numOfPages), (pageHeight))
scrollView.pagingEnabled = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsverticalScrollIndicator = false
scrollView.scrollsToTop = false
for i in 0..numOfPages{
myViewController = MyViewController (number:(i+1))
myViewController.view.frame = CGRectMake (pageWidth*i),
(0),monospace!important; min-height:inherit!important">(pageWidth),monospace!important; min-height:inherit!important">(pageHeight))
scrollView.addSubview(myViewController.view)
}
.view.addSubview(scrollView)
}
}

--- 子页面 ---
22
number: Int !
colorMap=[
1: UIColor .blackColor(),
2: .orangeColor(),
3: .blueColor()
]
init (number initNumber: ){
.number = initNumer
. (nibNmae: nil ,bundle: )
}
viewDidLoad(){
numberLabel = UILabel (frame: (0,100,100))
numberLabel.center = .view.center
numberLabel.text = "第\(number)页"
numberLabel.textColor = .whiteColor()
.view.addSubview(numberLabel)
.view.backgroundColor = colorMap[number]
}
原文出自: www.hangge.com 转载请保留原文链接 http://www.hangge.com/blog/cache/detail_544.html

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...