You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository has been archived by the owner on Dec 18, 2017. It is now read-only.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// MARK: AKCollectionViewLayout
/**
Private. A subclass of UICollectionViewFlowLayout used in the collection view.
*/
private class AKCollectionViewLayout: UICollectionViewFlowLayout {
var delegate: AKCollectionViewLayoutDelegate!
var width: CGFloat!
var midX: CGFloat!
var maxAngle: CGFloat!
// MARK: AKPickerViewDelegateIntercepter
/**
Private. Used to hook UICollectionViewDelegate and throw it AKPickerView,
and if it conforms to UIScrollViewDelegate, also throw it to AKPickerView's delegate.
*/
private class AKPickerViewDelegateIntercepter: NSObject, UICollectionViewDelegate {
weak var pickerView: AKPickerView?
weak var delegate: UIScrollViewDelegate?
// MARK: - AKPickerView
// TODO: Make these delegate conformation private
/**
Horizontal picker view. This is just a subclass of UIView, contains a UICollectionView.
*/
public class AKPickerView: UIView, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, AKCollectionViewLayoutDelegate {
// MARK: - Properties
// MARK: Readwrite Properties
/// Readwrite. Data source of picker view.
public weak var dataSource: AKPickerViewDataSource? = nil
/// Readwrite. Delegate of picker view.
public weak var delegate: AKPickerViewDelegate? = nil {
didSet(delegate) {
self.intercepter.delegate = delegate
}
}
/// Readwrite. A font which used in NOT selected cells.
public lazy var font = UIFont.systemFont(ofSize: 20)
/// Readwrite. A font which used in selected cells.
public lazy var highlightedFont = UIFont.boldSystemFont(ofSize: 20)
/// Readwrite. A color of the text on NOT selected cells.
@IBInspectable public lazy var textColor: UIColor = UIColor.darkGray
/// Readwrite. A color of the text on selected cells.
@IBInspectable public lazy var highlightedTextColor: UIColor = UIColor.black
/// Readwrite. A float value which indicates the spacing between cells.
@IBInspectable public var interitemSpacing: CGFloat = 0.0
/// Readwrite. The style of the picker view. See AKPickerViewStyle.
public var pickerViewStyle = AKPickerViewStyle.wheel
/// Readwrite. A float value which determines the perspective representation which used when using AKPickerViewStyle.Wheel style.
@IBInspectable public var viewDepth: CGFloat = 1000.0 {
didSet {
self.collectionView.layer.sublayerTransform = self.viewDepth > 0.0 ? {
var transform = CATransform3DIdentity;
transform.m34 = -1.0 / self.viewDepth;
return transform;
}() : CATransform3DIdentity;
}
}
/// Readwrite. A boolean value indicates whether the mask is disabled.
@IBInspectable public var maskDisabled: Bool! = nil {
didSet {
self.collectionView.layer.mask = self.maskDisabled == true ? nil : {
let maskLayer = CAGradientLayer()
maskLayer.frame = self.collectionView.bounds
maskLayer.colors = [
UIColor.clear.cgColor,
UIColor.black.cgColor,
UIColor.black.cgColor,
UIColor.clear.cgColor]
maskLayer.locations = [0.0, 0.33, 0.66, 1.0]
maskLayer.startPoint = CGPoint(x: 0.0, y: 0.0)
maskLayer.endPoint = CGPoint(x: 1.0, y: 0.0)
return maskLayer
}()
}
}
// MARK: Readonly Properties
/// Readonly. Index of currently selected item.
public private(set) var selectedItem: Int = 0
/// Readonly. The point at which the origin of the content view is offset from the origin of the picker view.
public var contentOffset: CGPoint {
get {
return self.collectionView.contentOffset
}
}
// MARK: Private Properties
/// Private. A UICollectionView which shows contents on cells.
private var collectionView: UICollectionView!
/// Private. An intercepter to hook UICollectionViewDelegate then throw it picker view and its delegate
private var intercepter: AKPickerViewDelegateIntercepter!
/// Private. A UICollectionViewFlowLayout used in picker view's collection view.
private var collectionViewLayout: AKCollectionViewLayout {
let layout = AKCollectionViewLayout()
layout.delegate = self
return layout
}
// MARK: - Functions
// MARK: View Lifecycle
/**
Private. Initializes picker view's subviews and friends.
*/
private func initialize() {
self.collectionView?.removeFromSuperview()
self.collectionView = UICollectionView(frame: self.bounds, collectionViewLayout: self.collectionViewLayout)
self.collectionView.showsHorizontalScrollIndicator = false
self.collectionView.backgroundColor = UIColor.clear
self.collectionView.decelerationRate = UIScrollViewDecelerationRateFast
self.collectionView.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
self.collectionView.dataSource = self
self.collectionView.register(
AKCollectionViewCell.self,
forCellWithReuseIdentifier: NSStringFromClass(AKCollectionViewCell.self))
self.addSubview(self.collectionView)
self.intercepter = AKPickerViewDelegateIntercepter(pickerView: self, delegate: self.delegate)
self.collectionView.delegate = self.intercepter
self.maskDisabled = self.maskDisabled == nil ? false : self.maskDisabled
}
public init() {
super.init(frame: CGRect(x: 0.0, y: 0.0, width: 0.0, height: 0.0))
self.initialize()
}
public override init(frame: CGRect) {
super.init(frame: frame)
self.initialize()
}
public required init!(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initialize()
}
deinit {
self.collectionView.delegate = nil
}
// MARK: Layout
public override func layoutSubviews() {
super.layoutSubviews()
if self.dataSource != nil && self.dataSource!.numberOfItemsInPickerView(pickerView: self) > 0 {
self.collectionView.collectionViewLayout = self.collectionViewLayout
self.scrollToItem(item: self.selectedItem, animated: false)
}
self.collectionView.layer.mask?.frame = self.collectionView.bounds
}
public override var intrinsicContentSize: CGSize {
return CGSize(width: UIViewNoIntrinsicMetric, height: max(self.font.lineHeight, self.highlightedFont.lineHeight))
}
// MARK: Calculation Functions
/**
Private. Used to calculate bounding size of given string with picker view's font and highlightedFont
:param: string A NSString to calculate size
:returns: A CGSize which contains given string just.
*/
private func sizeForString(string: NSString) -> CGSize {
let size = string.size(attributes: [NSFontAttributeName: self.font])
let highlightedSize = string.size(attributes: [NSFontAttributeName: self.highlightedFont])
return CGSize(
width: ceil(max(size.width, highlightedSize.width)),
height: ceil(max(size.height, highlightedSize.height)))
}
/**
Private. Used to calculate the x-coordinate of the content offset of specified item.
:param: item An integer value which indicates the index of cell.
:returns: An x-coordinate of the cell whose index is given one.
*/
private func offsetForItem(item: Int) -> CGFloat {
var offset: CGFloat = 0
for i in 0 ..< item {
let indexPath = IndexPath(item: i, section: 0)
let cellSize = self.collectionView(self.collectionView!, layout: self.collectionView.collectionViewLayout, sizeForItemAt: indexPath)
offset += cellSize.width
}
let firstIndexPath = IndexPath(item: 0, section: 0)
let firstSize = self.collectionView(self.collectionView, layout: self.collectionView.collectionViewLayout, sizeForItemAt: firstIndexPath)
let selectedIndexPath = IndexPath(item: item, section: 0)
let selectedSize = self.collectionView(self.collectionView, layout: self.collectionView.collectionViewLayout, sizeForItemAt: selectedIndexPath)
offset -= (firstSize.width - selectedSize.width) / 2.0
return offset
}
// MARK: View Controls
/**
Reload the picker view's contents and styles. Call this method always after any property is changed.
*/
public func reloadData() {
self.invalidateIntrinsicContentSize()
self.collectionView.collectionViewLayout.invalidateLayout()
self.collectionView.reloadData()
if self.dataSource != nil && self.dataSource!.numberOfItemsInPickerView(pickerView: self) > 0 {
self.selectItem(item: self.selectedItem, animated: false, notifySelection: false)
}
}
/**
Move to the cell whose index is given one without selection change.
:param: item An integer value which indicates the index of cell.
:param: animated True if the scrolling should be animated, false if it should be immediate.
*/
public func scrollToItem(item: Int, animated: Bool = false) {
switch self.pickerViewStyle {
case .flat:
self.collectionView.scrollToItem(
at: IndexPath(
item: item,
section: 0),
at: .centeredHorizontally,
animated: animated)
case .wheel:
self.collectionView.setContentOffset(
CGPoint(
x: self.offsetForItem(item: item),
y: self.collectionView.contentOffset.y),
animated: animated)
}
}
/**
Select a cell whose index is given one and move to it.
:param: item An integer value which indicates the index of cell.
:param: animated True if the scrolling should be animated, false if it should be immediate.
*/
public func selectItem(item: Int, animated: Bool = false) {
self.selectItem(item: item, animated: animated, notifySelection: true)
}
/**
Private. Select a cell whose index is given one and move to it, with specifying whether it calls delegate method.
:param: item An integer value which indicates the index of cell.
:param: animated True if the scrolling should be animated, false if it should be immediate.
:param: notifySelection True if the delegate method should be called, false if not.
*/
private func selectItem(item: Int, animated: Bool, notifySelection: Bool) {
self.collectionView.selectItem(
at: IndexPath(item: item, section: 0),
animated: animated,
scrollPosition: [])
self.scrollToItem(item: item, animated: animated)
self.selectedItem = item
if notifySelection {
self.delegate?.pickerView!(pickerView: self, didSelectItem: item)
}
}
// MARK: Delegate Handling
/**
Private.
*/
private func didEndScrolling() {
switch self.pickerViewStyle {
case .flat:
let center = self.convert(self.collectionView.center, to: self.collectionView)
if let indexPath = self.collectionView.indexPathForItem(at: center) {
self.selectItem(item: indexPath.item, animated: true, notifySelection: true)
}
case .wheel:
if let numberOfItems = self.dataSource?.numberOfItemsInPickerView(pickerView: self) {
for i in 0 ..< numberOfItems {
let indexPath = IndexPath(item: i, section: 0)
let cellSize = self.collectionView(self.collectionView, layout: self.collectionView.collectionViewLayout, sizeForItemAt: indexPath)
if self.offsetForItem(item: i) + cellSize.width / 2 > self.collectionView.contentOffset.x {
self.selectItem(item: i, animated: true, notifySelection: true)
break
}
}
}
}
}
// MARK: UICollectionViewDataSource
@nonobjc public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return self.dataSource != nil && self.dataSource!.numberOfItemsInPickerView(pickerView: self) > 0 ? 1 : 0
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.dataSource != nil ? self.dataSource!.numberOfItemsInPickerView(pickerView: self) : 0
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(AKCollectionViewCell.self), for: indexPath) as! AKCollectionViewCell
if let title = self.dataSource?.pickerView?(pickerView: self, titleForItem: indexPath.item) {
cell.label.text = title
cell.label.textColor = self.textColor
cell.label.highlightedTextColor = self.highlightedTextColor
cell.label.font = self.font
cell.font = self.font
cell.highlightedFont = self.highlightedFont
cell.label.bounds = CGRect(origin: CGPoint(x: 0.0, y: 0.0), size: self.sizeForString(string: title as NSString))
if let delegate = self.delegate {
delegate.pickerView?(pickerView: self, configureLabel: cell.label, forItem: indexPath.item)
if let margin = delegate.pickerView?(pickerView: self, marginForItem: indexPath.item) {
cell.label.frame = cell.label.frame.insetBy(dx: -margin.width, dy: -margin.height)
}
}
} else if let image = self.dataSource?.pickerView?(pickerView: self, imageForItem: indexPath.item) {
cell.imageView.image = image
}
cell._selected = (indexPath.item == self.selectedItem)
return cell
}
// MARK: UICollectionViewDelegateFlowLayout
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
var size = CGSize(width: self.interitemSpacing, height: collectionView.bounds.size.height)
if let title = self.dataSource?.pickerView?(pickerView: self, titleForItem: indexPath.item) {
size.width += self.sizeForString(string: title as NSString).width
if let margin = self.delegate?.pickerView?(pickerView: self, marginForItem: indexPath.item) {
size.width += margin.width * 2
}
} else if let image = self.dataSource?.pickerView?(pickerView: self, imageForItem: indexPath.item) {
size.width += image.size.width
}
return size
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0.0
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0.0
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
let number = self.collectionView(collectionView, numberOfItemsInSection: section)
let firstIndexPath = IndexPath(item: 0, section: section)
let firstSize = self.collectionView(collectionView, layout: collectionView.collectionViewLayout, sizeForItemAt: firstIndexPath)
let lastIndexPath = IndexPath(item: number - 1, section: section)
let lastSize = self.collectionView(collectionView, layout: collectionView.collectionViewLayout, sizeForItemAt: lastIndexPath)
return UIEdgeInsetsMake(
0, (collectionView.bounds.size.width - firstSize.width) / 2,
0, (collectionView.bounds.size.width - lastSize.width) / 2
)
}
// MARK: UICollectionViewDelegate
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.selectItem(item: indexPath.item, animated: true)
}
// MARK: UIScrollViewDelegate
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
self.delegate?.scrollViewDidEndDecelerating?(scrollView)
self.didEndScrolling()
}
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
self.delegate?.scrollViewDidEndDragging?(scrollView, willDecelerate: decelerate)
if !decelerate {
self.didEndScrolling()
}
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
self.delegate?.scrollViewDidScroll?(scrollView)
CATransaction.begin()
CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions)
self.collectionView.layer.mask?.frame = self.collectionView.bounds
CATransaction.commit()
}
// MARK: AKCollectionViewLayoutDelegate
fileprivate func pickerViewStyleForCollectionViewLayout(layout: AKCollectionViewLayout) -> AKPickerViewStyle {
return self.pickerViewStyle
}
Sign up for freeto subscribe to this conversation on GitHub.
Already have an account?
Sign in.
Labels
None yet
4 participants
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
No description provided.