Skip to content
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
}
}
}