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

Implemented intrinsicContentSize; Simplified repeating code #11

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
34 changes: 20 additions & 14 deletions SegmentedControl/SegmentedControl.swift
Original file line number Diff line number Diff line change
Expand Up @@ -268,33 +268,30 @@ open class SegmentedControl: UIControl {
}
}
}

open override var intrinsicContentSize: CGSize {
return CGSize(width: totalContentWidth(), height: frame.height)
}
}

public extension SegmentedControl {
// MARK: - Events
fileprivate func update() {
scrollView.frame = CGRect(origin: CGPoint.zero, size: frame.size)
scrollView.isScrollEnabled = isUserDragEnabled

switch layoutPolicy {
case .fixed:
scrollView.contentSize = CGSize(width: totalSegmentsWidth(), height: frame.height)
scrollView.contentInset = UIEdgeInsets.zero
case .dynamic:
scrollView.contentSize = CGSize(width: totalSegmentsWidth() + contentInset.left + contentInset.right, height: frame.height)
if (totalSegmentsWidth() + contentInset.left + contentInset.right) < frame.width {
let padding = (frame.width - totalSegmentsWidth()) / 2
scrollView.contentInset = UIEdgeInsets(top: 0, left: padding - contentInset.left, bottom: 0, right: padding - contentInset.right)
} else {
scrollView.contentInset = UIEdgeInsets.zero
}
scrollView.contentSize = CGSize(width: totalContentWidth(), height: frame.height)
scrollView.contentInset = UIEdgeInsets.zero

if layoutPolicy == .dynamic && totalContentWidth() < frame.width {
let padding = (frame.width - totalSegmentsWidth()) / 2
scrollView.contentInset = UIEdgeInsets(top: 0, left: padding - contentInset.left, bottom: 0, right: padding - contentInset.right)
}

scrollToSelectedIndex(animated: false)
}

fileprivate func scrollToSelectedIndex(animated: Bool) {
if layoutPolicy == .dynamic && (totalSegmentsWidth() + contentInset.left + contentInset.right) < frame.width {
if layoutPolicy == .dynamic && totalContentWidth() < frame.width {
return
}

Expand Down Expand Up @@ -769,4 +766,13 @@ public extension SegmentedControl {
return titleSizes[0..<index].enumerated().map { singleSegmentWidth(at: $0.offset) }
}
}

fileprivate func totalContentWidth() -> CGFloat {
switch layoutPolicy {
case .fixed:
return totalSegmentsWidth()
case .dynamic:
return totalSegmentsWidth() + contentInset.left + contentInset.right
}
}
}