Skip to content

Instantly share code, notes, and snippets.

@christianselig
Created September 3, 2021 18:14
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save christianselig/67261703f03f1e92f780b667c69903ef to your computer and use it in GitHub Desktop.
Save christianselig/67261703f03f1e92f780b667c69903ef to your computer and use it in GitHub Desktop.
Adding an image to a UIAlertController
extension UIAlertController {
/// Creates a view controller for notifying the user that a conversion is occurring. Accepts a block that is executed upon conversion completion.
static func createConvertingAlertController(onConversionCompletion: @escaping () -> Void) -> UIAlertController {
// The title font corresponds to Dynamic Type style "Headline"
let titleFont = UIFont.preferredFont(forTextStyle: .headline)
let calculatorImageView = UIImageView(image: UIImage(named: "calculator.fill", in: nil, with: UIImage.SymbolConfiguration(font: UIFont.systemFont(ofSize: titleFont.pointSize * 2.0, weight: .semibold))))
let measuringAttributedStringHeight = NSAttributedString(string: "Penguin", attributes: [.font: titleFont]).boundingRect(with: .zero, options: [.usesFontLeading, .usesLineFragmentOrigin], context: nil).height
let desiredOffset = 15.0 + calculatorImageView.bounds.height
let totalNewlinePrefixes = Int((desiredOffset / measuringAttributedStringHeight).rounded())
let alertController = UIAlertController(title: convertingTitle(withTotalNewlines: totalNewlinePrefixes), message: "Trying to remember long division… carry the 4…", preferredStyle: .alert)
let yOffset = 20.0
calculatorImageView.frame.origin = CGPoint(x: (alertController.view.bounds.width - calculatorImageView.bounds.width) / 2.0, y: yOffset)
calculatorImageView.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin]
calculatorImageView.tintColor = .secondaryLabel
alertController.view.addSubview(calculatorImageView)
let displayDurationMS = (2_500 ... 4_200).randomElement()!
let displayDurationSeconds = TimeInterval(displayDurationMS) / 1_000
let numbersTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { timer in
alertController.title = convertingTitle(withTotalNewlines: totalNewlinePrefixes)
}
delay(displayDurationSeconds) {
numbersTimer.invalidate()
onConversionCompletion()
alertController.dismiss(animated: true, completion: nil)
}
return alertController
}
private static func convertingTitle(withTotalNewlines totalNewlines: Int) -> String {
let newlinePrefixes = [String](repeating: "\n", count: totalNewlines).joined()
let numberRange = 100 ... 999
return "\(newlinePrefixes)Converting… \(numberRange.randomElement()!)"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment