Created
June 13, 2019 19:26
-
-
Save SebastianOsinski/c91422a7f431fd36981fd8a7787bf794 to your computer and use it in GitHub Desktop.
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
import SwiftUI | |
struct NumbersCollectionView : UIViewRepresentable { | |
@Binding var numbers: [Int] | |
func makeUIView(context: Context) -> UICollectionView { | |
let layout = UICollectionViewFlowLayout() | |
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) | |
collectionView.backgroundColor = .white | |
collectionView.register(NumberCell.self, forCellWithReuseIdentifier: "Cell") | |
let dataSource = UICollectionViewDiffableDataSource<Int, Int>(collectionView: collectionView) { (collectionView, indexPath, id) -> UICollectionViewCell? in | |
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! NumberCell | |
cell.number = id | |
return cell | |
} | |
context.coordinator.dataSource = dataSource | |
collectionView.dataSource = dataSource | |
return collectionView | |
} | |
func updateUIView(_ uiView: UICollectionView, context: Context) { | |
let snapshot = NSDiffableDataSourceSnapshot<Int, Int>() | |
snapshot.appendSections([0]) | |
snapshot.appendItems(numbers) | |
context.coordinator.dataSource.apply(snapshot, animatingDifferences: true) | |
} | |
func makeCoordinator() -> Coordinator { | |
return Coordinator() | |
} | |
final class Coordinator: NSObject { | |
var dataSource: UICollectionViewDiffableDataSource<Int, Int>! | |
} | |
} | |
private final class NumberCell: UICollectionViewCell { | |
var number: Int? { | |
didSet { | |
numberLabel.text = number.map(String.init) | |
} | |
} | |
private let numberLabel = UILabel() | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
contentView.addSubview(numberLabel) | |
contentView.backgroundColor = .systemYellow | |
numberLabel.translatesAutoresizingMaskIntoConstraints = false | |
NSLayoutConstraint.activate([ | |
numberLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor), | |
numberLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor) | |
]) | |
} | |
override func layoutSubviews() { | |
super.layoutSubviews() | |
contentView.layer.cornerRadius = contentView.frame.width / 2.0 | |
} | |
required init?(coder: NSCoder) { | |
fatalError("init(coder:) has not been implemented") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment