Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import UIKit
- enum ScrollDirection {
- case left
- case right
- }
- class PagerController: UIViewController {
- var pager: PagerView? {
- return view as? PagerView
- }
- var pagesCount = 5 {
- didSet {
- pager?.pagesCount = min(5, pagesCount)
- if pagesCount > 5 {
- pager?.mode = .scroll
- } else {
- pager?.mode = .noScroll
- }
- }
- }
- var current = 0 {
- didSet {
- guard let pager = pager, current != oldValue else {return}
- guard pager.mode != .noScroll else {
- pager.current = current
- return
- }
- let direction: ScrollDirection = current < oldValue ? .right : .left
- if direction == .left {
- if pager.current == 3, current < pagesCount - 1 {
- pager.animate(direction) {
- pager.current = self.current < self.pagesCount - 1 ? 3 : 4
- }
- } else {
- pager.current = min(4, pager.current + 1)
- }
- } else if direction == .right {
- if pager.current == 1, current > 0 {
- pager.animate(.right) {
- pager.current = self.current > 0 ? 1 : 0
- }
- } else {
- pager.current = max(0, pager.current - 1)
- }
- }
- }
- }
- override func viewDidLoad() {
- super.viewDidLoad()
- }
- }
- class PagerView: UIView {
- enum PagerMode {
- case noScroll
- case scroll
- case leftScroll
- case rightScroll
- }
- var mode: PagerMode = .noScroll {
- didSet {
- switch mode {
- case .leftScroll, .rightScroll:
- setNeedsDisplay()
- default:
- ()
- }
- }
- }
- var pagesCount = 5
- var current = 0 {
- didSet {
- setNeedsDisplay()
- }
- }
- private let sizes: [[Int]] = [[8,6,4,3,2], [6,8,6,4,3], [4,6,8,6,4], [3,4,6,8,6], [2,3,4,6,8]]
- private func pointSize(forIndex index: Int) -> Int {
- guard mode != .noScroll else {return 8}
- guard index > -1, index < 5 else {return 6}
- return sizes[current][index]
- }
- override func draw(_ rect: CGRect) {
- var path = UIBezierPath()
- path.lineWidth = 1
- for i in -1..<pagesCount+1 {
- if i == -1, mode != .rightScroll {continue}
- if i == pagesCount, mode != .leftScroll {continue}
- if i == 0, mode == .leftScroll {continue}
- if i == pagesCount - 1, mode == .rightScroll {continue}
- if i == current {
- UIColor.orange.setStroke()
- UIColor.orange.setFill()
- } else {
- UIColor.lightGray.setStroke()
- UIColor.lightGray.setFill()
- }
- let size = CGFloat(pointSize(forIndex: i))
- path = UIBezierPath(ovalIn: CGRect(x: ((rect.width / 2) - 32) + CGFloat(i*14) + (8 - size)/2, y: (rect.height-size)/2, width: size, height: size))
- path.stroke()
- path.fill()
- }
- }
- func animate(_ direction: ScrollDirection, completion: @escaping () -> Void) {
- mode = direction == .left ? .leftScroll : .rightScroll
- current = direction == .left ? 4 : 0
- UIView.animate(withDuration: 0.3, animations: {
- self.transform = CGAffineTransform(translationX: direction == .left ? -14 : 14, y: 0)
- }, completion: { _ in
- self.transform = .identity
- completion()
- self.mode = .scroll
- })
- }
- }
Add Comment
Please, Sign In to add comment