Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added tab bar centering #1112

Merged
merged 1 commit into from
Jul 6, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 34 additions & 3 deletions Sources/iOS/TabBar.swift
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,12 @@ public enum TabBarStyle: Int {
case scrollable
}

public enum TabBarCenteringStyle {
case never
case whenNeeded
case always
}

open class TabBar: Bar {
/// A dictionary of TabItemLineStates to UIColors for the line.
fileprivate var lineColorForState = [TabItemLineState: UIColor]()
Expand Down Expand Up @@ -229,6 +235,13 @@ open class TabBar: Bar {
layoutSubviews()
}
}

/// An enum that determines the tab bar centering style.
open var tabBarCenteringStyle = TabBarCenteringStyle.never {
didSet {
layoutSubviews()
}
}

/// A reference to the scroll view when the tab bar style is scrollable.
open let scrollView = UIScrollView()
Expand Down Expand Up @@ -625,9 +638,27 @@ fileprivate extension TabBar {
return
}

if !scrollView.bounds.contains(v.frame) {
let contentOffsetX = (v.frame.origin.x < scrollView.bounds.minX) ? v.frame.origin.x : v.frame.maxX - scrollView.bounds.width
let normalizedOffsetX = min(max(contentOffsetX, 0), scrollView.contentSize.width - scrollView.bounds.width)
let contentOffsetX: CGFloat? = {
let shouldScroll = !scrollView.bounds.contains(v.frame)

switch tabBarCenteringStyle {
case .whenNeeded:
guard shouldScroll else {
return nil
}
fallthrough
case .always:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When we have case ..., we should always leave a space before the next case.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just let XCode format those lines. Not sure if I understood but will keep track of your changes :)

return v.center.x - bounds.width / 2
case .never:
guard shouldScroll else {
return nil
}
return v.frame.origin.x < scrollView.bounds.minX ? v.frame.origin.x : v.frame.maxX - scrollView.bounds.width
}
}()

if let x = contentOffsetX {
let normalizedOffsetX = min(max(x, 0), scrollView.contentSize.width - scrollView.bounds.width)
scrollView.setContentOffset(CGPoint(x: normalizedOffsetX, y: 0), animated: true)
}
}
Expand Down