一个使用Swift写的PageMenu。


一个使用Swift写的PageMenu。没有那么多接口,自己可以根据实际需要扩展。写这个的目的一是为了练手,毕竟工作中使用Swift极少,再一个,PageMenu使用场景挺多的,我遇到过好几次,这次做一个总结。

项目地址:https://github.com/ChenYalun/PageMenu

一、思路

MenuStyle: 用于标题的样式配置
PageTitleView: 私有的单个标题控件
PageTitle: 标题区视图
PageContent: 内容区视图
PageMenu: 继承自UIViewController的视图控制器,用于连接PageTitle和PageContent
UIColor+RGB: 一些对UIColor的拓展,主要是支持RGB的方式设置颜色

二、代码

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 MenuStyle: UIView {
// 标题之间的间距
var margin: CGFloat = 10
// 默认颜色
var defaultColor = UIColor(r: 0, g: 0, b: 0)
// 默认字体
var defaultFont = UIFont.systemFont(ofSize: 17)
// 选中态颜色
var selectedColor = UIColor(r: 239, g: 154, b: 64)
// 选中态字体
var selectedFont = UIFont.systemFont(ofSize: 18)

// 指示条高度, 为0表示隐藏
var lineHeight: CGFloat = 2
// 指示条宽度, 为0表示自适应
var lineWidth: CGFloat = 0
// 指示条颜色, 默认与selectedColor保持一致
var lineColor: UIColor?
// 是否开启指示条颜色渐变
var lineColorGradual = true
// 指示条圆角
var lineCornerRadius: CGFloat = 2

// 标题区的frame
var pageTitleFrame = CGRect(x: 0, y: 20, width: UIScreen.main.bounds.width, height: 25)
// 标题区与内容区的间距
var titleContentMargin: CGFloat = 5
}

PageTitle

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
import UIKit

// 代理
protocol PageTitleDelegate : class {
func pageTitleDidSelected(pageTitle: PageTitle, pageTitleView: PageTitleView)
}

// 标题视图组件
class PageTitleView: UIView {
// 索引
var index: Int = 0
// 标题
var title: String?
// 渐变颜色
var color: UIColor? {
didSet {
label.textColor = color
}
}
// 样式
fileprivate var style: MenuStyle
// 选中状态
fileprivate var isSelected: Bool = false {
didSet { reloadState() }// 刷新数据
}
// 自身宽度
fileprivate var width: CGFloat {
return title?.size(withAttributes: [NSAttributedString.Key.font: font]).width ?? 0
}
// 字体大小
fileprivate var font: UIFont { return isSelected ? style.selectedFont : style.defaultFont }
// 字体颜色
fileprivate var fontColor: UIColor { return isSelected ? style.selectedColor : style.defaultColor }
// 点击回调
fileprivate var tapCallBack: ((_ view: PageTitleView) -> Void)?
private lazy var label: UILabel = {
let label = UILabel()
let gesture = UITapGestureRecognizer(target: self, action: #selector(action(_:)))
label.addGestureRecognizer(gesture)
label.isUserInteractionEnabled = true
return label
}()
init(title: String?, isSelected: Bool, style: MenuStyle) {
self.title = title
self.isSelected = isSelected
self.style = style
super.init(frame: CGRect.zero)
reloadState()
self.addSubview(label)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// 动态链接
@objc fileprivate func action(_ tap: UITapGestureRecognizer) {
if tapCallBack != nil {
tapCallBack!(self)
}
}
// 刷新数据
private func reloadState() {
label.text = title
label.textColor = fontColor
label.font = font
label.sizeToFit()
}
}

// 标题视图
class PageTitle: UIView {
// 代理
weak var delegate: PageTitleDelegate?
private var titleList: [String]
private lazy var scrollView: UIScrollView = {
var scrollView = UIScrollView(frame: bounds)
scrollView.showsHorizontalScrollIndicator = false
addSubview(scrollView)
return scrollView
}()
// 指示器
private lazy var lineView: UIView = {
var lineView = UIView()
lineView.backgroundColor = menuStyle.lineColor ?? menuStyle.selectedColor
lineView.layer.cornerRadius = menuStyle.lineCornerRadius
lineView.layer.masksToBounds = true
scrollView.addSubview(lineView)
return lineView
}()
// 样式
private var menuStyle: MenuStyle
// 当前选中标题
private var currentSelectedView: PageTitleView?
// 标题列表
private var titleViewList = [PageTitleView]()
init(frame: CGRect, menuStyle: MenuStyle, titleList: [String]) {
self.menuStyle = menuStyle
self.titleList = titleList
super.init(frame: frame)
setupSubViews()
}
private func setupSubViews() {
var totalWidth: CGFloat = 0
// 设置子控件
for (idx, title) in titleList.enumerated() {
let view = PageTitleView(title: title as String, isSelected: false, style: menuStyle)
view.index = idx
titleViewList.append(view)
let x = CGFloat(idx + 1) * menuStyle.margin + totalWidth
view.frame = CGRect(x: x, y: 0, width: view.width, height: frame.height - menuStyle.lineHeight)
totalWidth += view.width
scrollView.addSubview(view)
view.tapCallBack = { [weak self] view in
guard let self = self else { return }
self.changeToSelectedIndex(idx: view.index)
}
}
scrollView.contentSize = CGSize(width: totalWidth + CGFloat(titleList.count + 1) * menuStyle.margin, height: 0)
// 默认选中的索引 0
changeToSelectedIndex()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}

// MARK: 切换过程中需要调用的函数
extension PageTitle {
private func changeToSelectedIndex(idx: Int = 0, progress: CGFloat = 1) {
// 索引值越界
if idx > titleViewList.count - 1 || idx < 0 || titleViewList.count <= 0 { return }
var fromView, toView: PageTitleView
if currentSelectedView == nil {
fromView = titleViewList.first!
toView = fromView
} else {
fromView = currentSelectedView!
toView = titleViewList[idx]
// 同一个标题
if fromView == toView { return }
}
if menuStyle.lineHeight != 0 {
refreshBottomLineFrame(fromView.frame, toView.frame, progress)
}
if menuStyle.lineColorGradual {
refreshTitleViewColor(fromView, toView, progress)
}
if progress == 1 {
refreshTitleViewState(fromView, toView)
}
}
// 设置指示条frame
private func refreshBottomLineFrame(_ from: CGRect, _ to: CGRect, _ progress: CGFloat) {
var from = from
var to = to
let lineHeight = menuStyle.lineHeight
let lineWidth = menuStyle.lineWidth
let y = frame.height - lineHeight
let isFixedLineWidth = lineWidth != 0
let fromWidth = isFixedLineWidth ? lineWidth : from.width
let toWidth = isFixedLineWidth ? lineWidth : to.width
let fromMinX = isFixedLineWidth ? from.midX - lineWidth * 0.5 : from.minX
let fromMaxX = isFixedLineWidth ? fromMinX + lineWidth : from.maxX
let toMinX = isFixedLineWidth ? to.midX - lineWidth * 0.5 : to.minX
let toMaxX = isFixedLineWidth ? toMinX + lineWidth : to.maxX
from = CGRect(x: fromMinX, y: y, width: fromWidth, height: lineHeight)
to = CGRect(x: toMinX, y: y, width: toWidth, height: lineHeight)
let isToLeft = toMinX < fromMinX // 向左
if progress < 0.5 {
if isToLeft { // 向左移动
let offsetWidth = (fromMinX - toMinX) * 2 * progress
lineView.frame = CGRect(x: fromMinX - offsetWidth, y: y, width: fromMaxX - fromMinX + offsetWidth, height: lineHeight)
} else {
let offsetWidth = (toMaxX - fromMaxX) * 2 * progress
lineView.frame = CGRect(x: fromMinX, y: y, width:from.width + offsetWidth, height: lineHeight)
}
} else {
if isToLeft { // 向左移动
let offsetWidth = (fromMaxX - to.maxX) * (1 - (progress - 0.5) * 2)
lineView.frame = CGRect(x: toMinX, y: y, width:to.width + offsetWidth, height: lineHeight)
} else {
let offsetWidth = (toMinX - fromMinX) * (1 - (progress - 0.5) * 2)
lineView.frame = CGRect(x: toMinX - offsetWidth, y: y, width:toMaxX - toMinX + offsetWidth, height: lineHeight)
}
}
}
// 刷新标题状态
private func refreshTitleViewState(_ fromView: PageTitleView, _ toView: PageTitleView) {
// 更新currentSelectedView
currentSelectedView?.isSelected = false
toView.isSelected = true
currentSelectedView = toView

// 设置标题居中
let width = scrollView.bounds.width
let contentWidth = scrollView.contentSize.width
var offsetX = toView.center.x - width * 0.5
offsetX = max(offsetX, 0)
offsetX = min(contentWidth - width, offsetX)
if contentWidth <= width { // 保持居中
let viewWidth = CGFloat(titleViewList.last?.frame.maxX ?? 0) - CGFloat(titleViewList.first?.frame.minX ?? 0)
offsetX = -(width - viewWidth) * 0.5 + menuStyle.margin
}
scrollView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true)
if delegate != nil {
delegate?.pageTitleDidSelected(pageTitle: self, pageTitleView: toView)
}
}
// 标题颜色渐变
private func refreshTitleViewColor(_ fromView: PageTitleView, _ toView: PageTitleView, _ progress: CGFloat) {
let toRGB = UIColor.rgbValue(menuStyle.selectedColor)
let fromRGB = UIColor.rgbValue(menuStyle.defaultColor)
let deltaRGB = (toRGB.0 - fromRGB.0, toRGB.1 - fromRGB.1, toRGB.2 - fromRGB.2)
fromView.color = UIColor(r: toRGB.0 - deltaRGB.0 * progress, g: toRGB.1 - deltaRGB.1 * progress, b: toRGB.2 - deltaRGB.2 * progress)
toView.color = UIColor(r: fromRGB.0 + deltaRGB.0 * progress, g: fromRGB.1 + deltaRGB.1 * progress, b: fromRGB.2 + deltaRGB.2 * progress)
}
}

// MARK: PageContentDelegate
extension PageTitle : PageContentDelegate {
func pageContentDidChange(pageContent: PageContent, targetIndex: Int, progress: CGFloat) {
changeToSelectedIndex(idx: targetIndex, progress: progress)
}
}

PageContent

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import UIKit

// 代理
protocol PageContentDelegate : class {
func pageContentDidChange(pageContent: PageContent, targetIndex: Int, progress: CGFloat)
}

class PageContent: UIView {
weak var delegate: PageContentDelegate?
private var controllerList: [UIViewController]
private let identifier = "PageMenu_CollectionView_Identifier"
private var currentIndex = 0
private var shouldCallDelegate = false
private lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.itemSize = bounds.size
layout.scrollDirection = .horizontal
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
var collectionView = UICollectionView(frame: bounds, collectionViewLayout: layout)
collectionView.dataSource = self as UICollectionViewDataSource
collectionView.delegate = self as UICollectionViewDelegate
collectionView.showsHorizontalScrollIndicator = false
collectionView.scrollsToTop = false
collectionView.isPagingEnabled = true
collectionView.bounces = false
collectionView.backgroundColor = UIColor.white
// 注册cell
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: identifier)
addSubview(collectionView)
return collectionView
}()
init(frame: CGRect, controllerList: [UIViewController]) {
self.controllerList = controllerList
super.init(frame: frame)
self.collectionView.reloadData()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}

// MARK: UICollectionViewDataSource
extension PageContent : UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return controllerList.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath)
let view = controllerList[indexPath.row].view!
view.frame = cell.bounds
cell.contentView.addSubview(view)
return cell
}
}

// MARK: UIScrollViewDelegate
extension PageContent : UIScrollViewDelegate {
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let index = Int(scrollView.contentOffset.x / scrollView.bounds.width)
currentIndex = index
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
shouldCallDelegate = true
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if !shouldCallDelegate { return }
let width = scrollView.bounds.width
let offsetX = scrollView.contentOffset.x - CGFloat(currentIndex) * width
let offsetIndex = offsetX > 0 ? 1 : -1
let progress = abs(offsetX) / width
if delegate != nil {
delegate?.pageContentDidChange(pageContent: self, targetIndex: currentIndex + offsetIndex, progress: progress)
}
}
}

// MARK: PageTitleDelegate
extension PageContent : PageTitleDelegate {
internal func pageTitleDidSelected(pageTitle: PageTitle, pageTitleView: PageTitleView) {
shouldCallDelegate = false
collectionView.scrollToItem(at: IndexPath(item: pageTitleView.index, section: 0), at: .left, animated: false)
currentIndex = pageTitleView.index
}
}
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
32
33
34
import UIKit

class PageMenu : UIViewController {
var pageTitle: PageTitle
var pageContent: PageContent
var menuStyle: MenuStyle
private var controllerList: [UIViewController]
init(_ menuStyle: MenuStyle, _ controllerList: [UIViewController]) {
var titleList = [String]()
for controller in controllerList {
titleList.append(controller.title ?? "null")
}
self.pageTitle = PageTitle(frame: menuStyle.pageTitleFrame, menuStyle: menuStyle, titleList: titleList)
self.pageContent = PageContent(frame: CGRect(x: pageTitle.frame.minX, y: pageTitle.frame.maxY + menuStyle.titleContentMargin, width: pageTitle.frame.width, height: UIScreen.main.bounds.height - pageTitle.frame.height), controllerList: controllerList)
self.menuStyle = menuStyle
self.controllerList = controllerList
super.init(nibName: nil, bundle: nil)
configureComponent()
}

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

private func configureComponent() {
view.addSubview(pageTitle)
view.addSubview(pageContent)
for controller in controllerList {
addChild(controller)
}
pageTitle.delegate = pageContent
pageContent.delegate = pageTitle
}
}

UIColor+RGB

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import Foundation
import UIKit
extension UIColor {
convenience init(r : CGFloat, g : CGFloat, b : CGFloat) {
self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: 1.0)
}

class func rgbValue(_ color : UIColor) -> (CGFloat, CGFloat, CGFloat) {
guard let components = color.cgColor.components else {
fatalError("颜色按照RGB设置")
}
return (components[0] * 255, components[1] * 255, components[2] * 255)
}
}

三、使用

简单配置一下MenuStyle,创建自己的视图控制器,就能直接使用了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
override func viewDidLoad() {
super.viewDidLoad()
var controllerList = [UIViewController]()
let style: MenuStyle = MenuStyle()
// 创建style并配置样式
style.margin = 30
style.defaultColor = UIColor(r: 135, g: 135, b: 135)
style.selectedColor = UIColor(r: 0, g: 0, b: 0)
// 创建控制器
let red = UIViewController()
red.view.backgroundColor = UIColor.red
red.title = "关注"
let blue = UIViewController()
blue.view.backgroundColor = UIColor.blue
blue.title = "热门"
controllerList = [red, blue]
// 创建PageMenu
let pageMenu = PageMenu(style, controllerList)
pageMenu.pageTitle.backgroundColor = UIColor(r: 45, g: 184, b: 105)
addChild(pageMenu)
view.addSubview(pageMenu.view)
}

四、效果

微博样式:

it之家样式:

五、总结

处理起来比较麻烦一点的就是,标题区指示条的frame渐变,要考虑左滑和右滑的情况,还要考虑进度progress的问题。不过还好,仔细想想都能解决的。

再一个,PageTitle和PageContent之间互相通信的方案,我选择的是代理。PageTitle是PageContent的代理,同时,PageContent又是PageTitle的代理。由PageMenu负责连接。