Skip to content

Instantly share code, notes, and snippets.

@chriseidhof
Created April 20, 2020 12:33
  • Star 24 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save chriseidhof/cb662d2161a59a0cd5babf78e3562272 to your computer and use it in GitHub Desktop.
TextAlert
//
// ContentView.swift
//
// Created by Chris Eidhof on 20.04.20.
// Copyright © 2020 objc.io. All rights reserved.
//
import SwiftUI
import UIKit
extension UIAlertController {
convenience init(alert: TextAlert) {
self.init(title: alert.title, message: nil, preferredStyle: .alert)
addTextField { $0.placeholder = alert.placeholder }
addAction(UIAlertAction(title: alert.cancel, style: .cancel) { _ in
alert.action(nil)
})
let textField = self.textFields?.first
addAction(UIAlertAction(title: alert.accept, style: .default) { _ in
alert.action(textField?.text)
})
}
}
struct AlertWrapper<Content: View>: UIViewControllerRepresentable {
@Binding var isPresented: Bool
let alert: TextAlert
let content: Content
func makeUIViewController(context: UIViewControllerRepresentableContext<AlertWrapper>) -> UIHostingController<Content> {
UIHostingController(rootView: content)
}
final class Coordinator {
var alertController: UIAlertController?
init(_ controller: UIAlertController? = nil) {
self.alertController = controller
}
}
func makeCoordinator() -> Coordinator {
return Coordinator()
}
func updateUIViewController(_ uiViewController: UIHostingController<Content>, context: UIViewControllerRepresentableContext<AlertWrapper>) {
uiViewController.rootView = content
if isPresented && uiViewController.presentedViewController == nil {
var alert = self.alert
alert.action = {
self.isPresented = false
self.alert.action($0)
}
context.coordinator.alertController = UIAlertController(alert: alert)
uiViewController.present(context.coordinator.alertController!, animated: true)
}
if !isPresented && uiViewController.presentedViewController == context.coordinator.alertController {
uiViewController.dismiss(animated: true)
}
}
}
public struct TextAlert {
public var title: String
public var placeholder: String = ""
public var accept: String = "OK"
public var cancel: String = "Cancel"
public var action: (String?) -> ()
}
extension View {
public func alert(isPresented: Binding<Bool>, _ alert: TextAlert) -> some View {
AlertWrapper(isPresented: isPresented, alert: alert, content: self)
}
}
struct ContentView: View {
@State var showsAlert = false
var body: some View {
VStack {
Text("Hello, World!")
Button("alert") {
self.showsAlert = true
}
}
.alert(isPresented: $showsAlert, TextAlert(title: "Title", action: {
print("Callback \($0 ?? "<cancel>")")
}))
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
@quintuschen
Copy link

If I put .alert on a view, say, a VStack that does not take the whole screen, it will add a padding on top and bottom of the VStack. Is there any way to get around with that?

@skywalkerlw
Copy link

There's a problem: the navigation bar title will never come in this case.

@chriseidhof
Copy link
Author

Hm, I'm not sure, I haven't looked at this code in a long time...

@LucasCoelho
Copy link

this somehow makes my hidden navigation bar appear even without presenting the alert

@daviscdev
Copy link

daviscdev commented Sep 16, 2021

Set the UIHostingController background color to clear will fix some black cover issue

func makeUIViewController(context: UIViewControllerRepresentableContext<AlertWrapper>) -> UIHostingController<Content> {
        let hosting = UIHostingController(rootView: content)
        hosting.view.backgroundColor = .clear
        return hosting
    }

@skirsche-ieffects
Copy link

skirsche-ieffects commented May 23, 2022

When I try it on iOS 15, it does not work well with the automatic keyboard avoidance introduced in iOS 14. The SwiftUI views below the alert move around when the keyboard for the alert's text field appears.

Other than wrapping everything in a ScrollView, the only workaround I've seen so far is setting .ignoresSafeArea(.keyboard) in combination with this:
https://steipete.com/posts/disabling-keyboard-avoidance-in-swiftui-uihostingcontroller/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment