加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 01:28:01 所属栏目:百科 来源:网络整理
导读:UIScrollView提供了以页面为单位滚动显示各个子页面内容的功能,每次手指滑动后会滚动一屏的内容。 要实现该功能,需要如下操作: 1,将UIScrollView的pagingEnabled属性设置成true 2,必须通过contentSize属性设置各个页面相加的宽度。比如iphone手机一屏宽
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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!