Skip to content

Instantly share code, notes, and snippets.

@pookjw
Created April 13, 2024 17:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pookjw/0325a619a1e8125ee22c3e8bf99373a4 to your computer and use it in GitHub Desktop.
Save pookjw/0325a619a1e8125ee22c3e8bf99373a4 to your computer and use it in GitHub Desktop.
import UIKit
import SwiftUI
final class TraitSelectionState: UITraitDefinition, UITraitBridgedEnvironmentKey {
static func read(from traitCollection: UITraitCollection) -> Bool {
traitCollection[TraitSelectionState.self]
}
static func write(to mutableTraits: inout any UIMutableTraits, value: Bool) {
fatalError("Forbidden")
}
static let defaultValue = false
static let identifier = "TraitSelectionState"
static let name = "TraitSelectionState"
}
final class CollectionViewCell: UICollectionViewCell {
override var traitCollection: UITraitCollection {
super.traitCollection.replacing(TraitSelectionState.self, value: isSelected)
}
override var configurationState: UICellConfigurationState {
var state = super.configurationState
state.traitCollection = state.traitCollection.replacing(TraitSelectionState.self, value: isSelected)
return state
}
override func updateConfiguration(using state: UICellConfigurationState) {
var state = state
state.traitCollection = state.traitCollection.replacing(TraitSelectionState.self, value: isSelected)
super.updateConfiguration(using: state)
}
}
extension EnvironmentValues {
var isSelected: Bool {
get {
self[TraitSelectionState.self]
}
}
}
struct ContentView: View {
@Environment(\.isSelected) private var isSelected
var body: some View {
Group {
if isSelected {
Color.blue
} else {
Color.red
}
}
.frame(height: 44.0)
.onChange(of: isSelected, initial: false) { oldValue, newValue in
print(newValue)
}
}
}
final class CollectionViewController: UICollectionViewController {
private let cellRegistration: UICollectionView.CellRegistration<CollectionViewCell, Void> = .init { cell, indexPath, itemIdentifier in
cell.contentConfiguration = UIHostingConfiguration {
ContentView()
}
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
100
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
collectionView.dequeueConfiguredReusableCell(using: cellRegistration, for: indexPath, item: ())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment