This repository was archived by the owner on Jun 17, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 441
Expand file tree
/
Copy pathMenuView.swift
More file actions
403 lines (343 loc) · 14.1 KB
/
MenuView.swift
File metadata and controls
403 lines (343 loc) · 14.1 KB
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//
// MenuView.swift
// PagingMenuController
//
// Created by Yusuke Kita on 5/9/15.
// Copyright (c) 2015 kitasuke. All rights reserved.
//
import UIKit
open class MenuView: UIScrollView {
public fileprivate(set) var currentMenuItemView: MenuItemView!
internal fileprivate(set) var menuItemViews = [MenuItemView]()
internal var onMove: ((MenuMoveState) -> Void)?
fileprivate var menuOptions: MenuViewCustomizable!
fileprivate var sortedMenuItemViews = [MenuItemView]()
fileprivate let contentView: UIView = {
$0.translatesAutoresizingMaskIntoConstraints = false
return $0
}(UIView(frame: .zero))
lazy fileprivate var underlineView: UIView = {
return UIView(frame: .zero)
}()
lazy fileprivate var roundRectView: UIView = {
$0.isUserInteractionEnabled = true
return $0
}(UIView(frame: .zero))
fileprivate var menuViewBounces: Bool {
switch menuOptions.displayMode {
case .standard(_, _, .scrollEnabledAndBouces),
.infinite(_, .scrollEnabledAndBouces): return true
default: return false
}
}
fileprivate var menuViewScrollEnabled: Bool {
switch menuOptions.displayMode {
case .standard(_, _, .scrollEnabledAndBouces),
.standard(_, _, .scrollEnabled),
.infinite(_, .scrollEnabledAndBouces),
.infinite(_, .scrollEnabled): return true
default: return false
}
}
fileprivate var contentOffsetX: CGFloat {
switch menuOptions.displayMode {
case .standard(_, let centerItem, _) where centerItem:
return centerOfScreenWidth
case .standard(_, let centerItem, _) where !centerItem:
if self.contentView.frame.width < self.frame.width {
return contentOffset.x
} else {
return contentOffsetXForCurrentPage
}
case .segmentedControl:
return contentOffset.x
case .infinite:
return centerOfScreenWidth
default:
return contentOffsetXForCurrentPage
}
}
fileprivate var centerOfScreenWidth: CGFloat {
let screenWidth: CGFloat
if let width = UIApplication.shared.keyWindow?.bounds.width {
screenWidth = width
} else {
screenWidth = UIScreen.main.bounds.width
}
return menuItemViews[currentPage].frame.midX - screenWidth / 2
}
fileprivate var contentOffsetXForCurrentPage: CGFloat {
guard menuItemCount > MinimumSupportedViewCount else { return 0.0 }
let ratio = CGFloat(currentPage) / CGFloat(menuItemCount - 1)
return (contentSize.width - frame.width) * ratio
}
fileprivate var currentIndex: Int = 0
// MARK: - Lifecycle
internal init(menuOptions: MenuViewCustomizable) {
super.init(frame: CGRect(x: 0, y: 0, width: 0, height: menuOptions.height))
if #available(iOS 10.0, *) {
self.accessibilityTraits = UIAccessibilityTraitTabBar
}
self.menuOptions = menuOptions
commonInit({ self.constructMenuItemViews(menuOptions) })
}
fileprivate func commonInit(_ constructor: () -> Void) {
setupScrollView()
layoutScrollView()
setupContentView()
layoutContentView()
setupRoundRectViewIfNeeded()
constructor()
layoutMenuItemViews()
setupUnderlineViewIfNeeded()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override open func layoutSubviews() {
super.layoutSubviews()
adjustmentContentInsetIfNeeded()
}
// MARK: - Internal method
internal func move(toPage page: Int, animated: Bool = true) {
// hide menu view when constructing itself
if !animated {
alpha = 0
}
let menuItemView = menuItemViews[page]
let previousPage = currentPage
let previousMenuItemView = currentMenuItemView
if let previousMenuItemView = previousMenuItemView,
page != previousPage {
previousMenuItemView.titleLabel.accessibilityTraits = UIAccessibilityTraitStaticText
onMove?(.willMoveItem(to: menuItemView, from: previousMenuItemView))
}
menuItemView.titleLabel.accessibilityTraits = UIAccessibilityTraitSelected
update(currentPage: page)
let duration = animated ? menuOptions.animationDuration : 0
UIView.animate(withDuration: duration, animations: { [unowned self] () -> Void in
self.focusMenuItem()
if self.menuOptions.selectedItemCenter {
self.positionMenuItemViews()
}
}) { [weak self] (_) in
guard let _ = self else { return }
// relayout menu item views dynamically
if case .infinite = self!.menuOptions.displayMode {
self!.relayoutMenuItemViews()
}
if self!.menuOptions.selectedItemCenter {
self!.positionMenuItemViews()
}
self!.setNeedsLayout()
self!.layoutIfNeeded()
// show menu view when constructing is done
if !animated {
self!.alpha = 1
}
if let previousMenuItemView = previousMenuItemView,
page != previousPage {
self!.onMove?(.didMoveItem(to: self!.currentMenuItemView, from: previousMenuItemView))
}
}
}
internal func updateMenuViewConstraints(_ size: CGSize) {
if case .segmentedControl = menuOptions.displayMode {
menuItemViews.forEach { $0.updateConstraints(size) }
}
setNeedsLayout()
layoutIfNeeded()
animateUnderlineViewIfNeeded()
animateRoundRectViewIfNeeded()
}
// MARK: - Private method
fileprivate func setupScrollView() {
backgroundColor = menuOptions.backgroundColor
showsHorizontalScrollIndicator = false
showsVerticalScrollIndicator = false
bounces = menuViewBounces
isScrollEnabled = menuViewScrollEnabled
isDirectionalLockEnabled = true
decelerationRate = menuOptions.deceleratingRate
scrollsToTop = false
translatesAutoresizingMaskIntoConstraints = false
}
fileprivate func layoutScrollView() {
let viewsDictionary = ["menuView": self]
let metrics = ["height": menuOptions.height]
NSLayoutConstraint.activate(
NSLayoutConstraint.constraints(withVisualFormat: "V:[menuView(height)]", options: [], metrics: metrics, views: viewsDictionary)
)
}
fileprivate func setupContentView() {
addSubview(contentView)
}
fileprivate func layoutContentView() {
// H:|[contentView]|
// V:|[contentView(==scrollView)]|
NSLayoutConstraint.activate([
contentView.leadingAnchor.constraint(equalTo: leadingAnchor),
contentView.trailingAnchor.constraint(equalTo: trailingAnchor),
contentView.topAnchor.constraint(equalTo: topAnchor),
contentView.bottomAnchor.constraint(equalTo: bottomAnchor),
contentView.heightAnchor.constraint(equalTo: heightAnchor)
])
}
fileprivate func constructMenuItemViews(_ menuOptions: MenuViewCustomizable) {
constructMenuItemViews({
return MenuItemView(menuOptions: menuOptions, menuItemOptions: menuOptions.itemsOptions[$0], addDiveder: $1)
})
}
fileprivate func constructMenuItemViews(_ constructor: (Int, Bool) -> MenuItemView) {
for index in 0..<menuItemCount {
let addDivider = index < menuItemCount - 1
let menuItemView = constructor(index % menuOptions.itemsOptions.count, addDivider)
menuItemView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(menuItemView)
menuItemViews.append(menuItemView)
}
sortMenuItemViews()
}
fileprivate func sortMenuItemViews() {
if !sortedMenuItemViews.isEmpty {
sortedMenuItemViews.removeAll()
}
if case .infinite = menuOptions.displayMode {
for i in 0..<menuItemCount {
let page = rawPage(i)
sortedMenuItemViews.append(menuItemViews[page])
}
} else {
sortedMenuItemViews = menuItemViews
}
}
fileprivate func layoutMenuItemViews() {
NSLayoutConstraint.deactivate(contentView.constraints)
for (index, menuItemView) in sortedMenuItemViews.enumerated() {
if index == 0 {
// H:|[menuItemView]
menuItemView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
} else {
if index == sortedMenuItemViews.count - 1 {
// H:[menuItemView]|
menuItemView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
}
// H:[previousMenuItemView][menuItemView]
let previousMenuItemView = sortedMenuItemViews[index - 1]
previousMenuItemView.trailingAnchor.constraint(equalTo: menuItemView.leadingAnchor, constant: 0).isActive = true
}
// V:|[menuItemView]|
NSLayoutConstraint.activate([
menuItemView.topAnchor.constraint(equalTo: contentView.topAnchor),
menuItemView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
])
}
setNeedsLayout()
layoutIfNeeded()
}
fileprivate func setupUnderlineViewIfNeeded() {
guard case let .underline(height, color, horizontalPadding, verticalPadding) = menuOptions.focusMode else { return }
let width = menuItemViews[currentPage].bounds.width - horizontalPadding * 2
underlineView.frame = CGRect(x: horizontalPadding, y: menuOptions.height - (height + verticalPadding), width: width, height: height)
underlineView.backgroundColor = color
contentView.addSubview(underlineView)
}
fileprivate func setupRoundRectViewIfNeeded() {
guard case let .roundRect(radius, _, verticalPadding, selectedColor) = menuOptions.focusMode else { return }
let height = menuOptions.height - verticalPadding * 2
roundRectView.frame = CGRect(x: 0, y: verticalPadding, width: 0, height: height)
roundRectView.layer.cornerRadius = radius
roundRectView.backgroundColor = selectedColor
contentView.addSubview(roundRectView)
}
fileprivate func animateUnderlineViewIfNeeded() {
guard case .underline(_, _, let horizontalPadding, _) = menuOptions.focusMode else { return }
let targetFrame = menuItemViews[currentPage].frame
underlineView.frame.origin.x = targetFrame.minX + horizontalPadding
underlineView.frame.size.width = targetFrame.width - horizontalPadding * 2
}
fileprivate func animateRoundRectViewIfNeeded() {
guard case .roundRect(_, let horizontalPadding, _, _) = menuOptions.focusMode else { return }
let targetFrame = menuItemViews[currentPage].frame
roundRectView.frame.origin.x = targetFrame.minX + horizontalPadding
roundRectView.frame.size.width = targetFrame.width - horizontalPadding * 2
}
fileprivate func relayoutMenuItemViews() {
sortMenuItemViews()
layoutMenuItemViews()
}
fileprivate func positionMenuItemViews() {
contentOffset.x = contentOffsetX
animateUnderlineViewIfNeeded()
animateRoundRectViewIfNeeded()
}
fileprivate func adjustmentContentInsetIfNeeded() {
switch menuOptions.displayMode {
case .standard(_, let centerItem, _) where centerItem: break
default: return
}
guard let firstMenuView = menuItemViews.first,
let lastMenuView = menuItemViews.last else { return }
var inset = contentInset
let halfWidth = frame.width / 2
inset.left = halfWidth - firstMenuView.frame.width / 2
inset.right = halfWidth - lastMenuView.frame.width / 2
contentInset = inset
}
fileprivate func focusMenuItem() {
let isSelected: (MenuItemView) -> Bool = { self.menuItemViews.index(of: $0) == self.currentPage }
// make selected item focused
menuItemViews.forEach {
$0.isSelected = isSelected($0)
if $0.isSelected {
self.currentMenuItemView = $0
}
}
// make selected item foreground
sortedMenuItemViews.forEach { $0.layer.zPosition = isSelected($0) ? 0 : -1 }
setNeedsLayout()
layoutIfNeeded()
}
}
extension MenuView: Pagable {
var currentPage: Int {
return currentIndex
}
var previousPage: Int {
return currentPage - 1 < 0 ? menuItemCount - 1 : currentPage - 1
}
var nextPage: Int {
return currentPage + 1 > menuItemCount - 1 ? 0 : currentPage + 1
}
func update(currentPage page: Int) {
currentIndex = page
}
}
extension MenuView {
func cleanup() {
contentView.removeFromSuperview()
switch menuOptions.focusMode {
case .underline: underlineView.removeFromSuperview()
case .roundRect: roundRectView.removeFromSuperview()
case .none: break
}
if !menuItemViews.isEmpty {
menuItemViews.forEach {
$0.cleanup()
$0.removeFromSuperview()
}
}
}
}
extension MenuView {
var menuItemCount: Int {
switch menuOptions.displayMode {
case .infinite: return menuOptions.itemsOptions.count * menuOptions.dummyItemViewsSet
default: return menuOptions.itemsOptions.count
}
}
fileprivate func rawPage(_ page: Int) -> Int {
let startIndex = currentPage - menuItemCount / 2
return (startIndex + page + menuItemCount) % menuItemCount
}
}