Last active
July 27, 2021 13:46
-
-
Save Koze/76456f9d7558f81f99a9d1eb7323ff12 to your computer and use it in GitHub Desktop.
Adding SwiftUI preview implementation to existing view class
This file contains hidden or 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
// | |
// TableViewCell.swift | |
// iOS12App | |
// | |
// Created by Kazuma Koze on 2020/03/05. | |
// Copyright © 2020 Climb App. All rights reserved. | |
// | |
import UIKit | |
import SwiftUI | |
class TableViewCell: UITableViewCell { | |
@IBOutlet weak var titleLabel: UILabel! | |
@IBOutlet weak var subheadLabel: UILabel! | |
@IBOutlet weak var bodyLabel: UILabel! | |
@IBOutlet weak var stackView: UIStackView! | |
override func awakeFromNib() { | |
super.awakeFromNib() | |
// for SwiftUI preview | |
setContentHuggingPriority(.defaultHigh, for: .vertical) | |
updateStackViewAxis(traitCollection.preferredContentSizeCategory.isAccessibilityCategory) | |
} | |
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { | |
super.traitCollectionDidChange(previousTraitCollection) | |
let isAccessibilityCategory = traitCollection.preferredContentSizeCategory.isAccessibilityCategory | |
if isAccessibilityCategory != previousTraitCollection?.preferredContentSizeCategory.isAccessibilityCategory { | |
updateStackViewAxis(isAccessibilityCategory) | |
} | |
} | |
private func updateStackViewAxis(_ isAccessibilityCategory: Bool) { | |
stackView.axis = isAccessibilityCategory ? .vertical : .horizontal | |
stackView.alignment = isAccessibilityCategory ? .leading : .center | |
} | |
// for SwiftUI preview | |
override var intrinsicContentSize: CGSize { | |
return systemLayoutSizeFitting(UIView.layoutFittingCompressedSize) | |
} | |
} | |
#if DEBUG | |
@available(iOS 13.0, *) | |
struct TableViewCellPreview: PreviewProvider, UIViewRepresentable { | |
typealias UIViewType = TableViewCell | |
static var previews: some View { | |
Group { | |
Self() | |
.environment(\.sizeCategory, .medium) | |
.previewLayout(.sizeThatFits) | |
Self() | |
.environment(\.sizeCategory, .accessibilityExtraExtraExtraLarge) | |
.previewLayout(.sizeThatFits) | |
} | |
} | |
func makeUIView(context: UIViewRepresentableContext<Self>) -> UIViewType { | |
let nib = UINib(nibName: String(describing: UIViewType.self), bundle: nil) | |
let cell = nib.instantiate(withOwner: nil, options: nil).first as! UIViewType | |
return cell | |
} | |
func updateUIView(_ uiView: UIViewType, context: UIViewRepresentableContext<Self>) { | |
} | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment