Skip to content

Instantly share code, notes, and snippets.

@PierceLBrooks
Created May 23, 2025 19:27
Show Gist options
  • Save PierceLBrooks/1bde730a58c9cf2ec00a2aa692a62632 to your computer and use it in GitHub Desktop.
Save PierceLBrooks/1bde730a58c9cf2ec00a2aa692a62632 to your computer and use it in GitHub Desktop.
// Author: Pierce Brooks
#if os(macOS)
import AppKit
#else
import UIKit
#endif
#if os(macOS)
public class ImageBaseViewController: NSViewController {}
#else
public class ImageBaseViewController: UIViewController {}
#endif
class ImageViewController: ImageBaseViewController {
#if os(macOS)
public let image: NSImage
#else
public let image: UIImage
#endif
#if os(macOS)
@available(*, unavailable)
public required init?(
coder aDecoder: NSCoder
) { nil }
public init(
image: NSImage
) {
self.image = image
super.init(nibName: nil, bundle: nil)
}
#else
public init(
image: UIImage
) {
self.image = image
super.init(coder: nil)
}
#endif
#if os(macOS)
private var someImageView: NSImageView? {
let theImageView = NSImageView()
theImageView.image = self.image
theImageView.translatesAutoresizingMaskIntoConstraints = false
return theImageView
}
#else
private var someImageView: UIImageView? {
let theImageView = UIImageView()
theImageView.image = self.image
theImageView.translatesAutoresizingMaskIntoConstraints = false
return theImageView
}
#endif
override func viewDidLoad() {
super.viewDidLoad()
let anImageView = someImageView
if (anImageView != nil) {
view.addSubview(anImageView!)
imageViewConstraints(imageView: anImageView!)
}
}
#if os(macOS)
func imageViewConstraints(imageView: NSImageView) {
imageView.widthAnchor.constraint(equalToConstant: 180).isActive = true
imageView.heightAnchor.constraint(equalToConstant: 180).isActive = true
imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 28).isActive = true
}
#else
func imageViewConstraints(imageView: UIImageView) {
imageView.widthAnchor.constraint(equalToConstant: 180).isActive = true
imageView.heightAnchor.constraint(equalToConstant: 180).isActive = true
imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 28).isActive = true
}
#endif
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment