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

注:代码已升级至Swift4

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

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

  1. UIScrollViewisPagingEnabled属性设置成true
  2. 必须通过contentSize属性设置各个页面相加的宽度。比如iPhone手机一屏宽度是320,如果有3个页面,则contentSize就需要设置为320*3=960
  3. 最好将showsHorizontalScrollIndicatorshowsVerticalScrollIndicator设置成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
29
30
31
import UIKit

class ViewController: UIViewController {
let numOfPages = 3
let pageWidth = 320
let pageHeight = 360

override func viewDidLoad() {
super.viewDidLoad()

//scrollView的初始化
let scrollView = UIScrollView()
scrollView.frame = self.view.bounds
//为了让内容横向滚动,设置横向内容宽度为3个页面的宽度总和
scrollView.contentSize = CGSize(width: pageWidth * numOfPages,
height: pageHeight)
scrollView.isPagingEnabled = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.scrollsToTop = false

//添加子页面
for i in 0..<numOfPages {
let myViewController = MyViewController(number:(i+1))
myViewController.view.frame = CGRect(x:pageWidth*i, y:0,
width:pageWidth, height: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
23
24
25
26
27
28
import UIKit

class MyViewController: UIViewController{
var number:Int!

let colorMap = [
1:UIColor.black,
2:UIColor.orange,
3:UIColor.blue
]

init(number initNumber:Int) {
self.number = initNumber
super.init(nibName:nil, bundle:nil)
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

override func viewDidLoad() {
let numberLabel = UILabel(frame:CGRect(x:130, y:50, width:50, height:30))
numberLabel.text = "第\(number!)页"
numberLabel.textColor = UIColor.white
self.view.addSubview(numberLabel)
self.view.backgroundColor = colorMap[number]
}
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :