Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI - Action sheet with no title, Alert.Button using View instead of Text

Is there any way to have no title section in an Action Sheet? The Action Sheet definition in the SwiftUI code is as follows:

public struct ActionSheet {
   /// Creates an action sheet with the provided buttons.
   public init(title: Text, message: Text? = nil, buttons: [ActionSheet.Button] = [.cancel()])
   /// A button representing an operation of an action sheet presentation.
   public typealias Button = Alert.Button
}

Since title only conforms to Text, I thought perhaps adding just Text("") would do the job; however, this instead keeps the space for the title empty, rather than removing it. Giving nil instead of Text("") also doesn't work.

Also, is there any way to give an Action Sheet's button a view, like with the following:

struct ActionItem: View {

  var body: some View {

    HStack {

        Image(systemName: "phone")

        Spacer()

        Text("Call 1-408-123-4567")
    }
  }
}
like image 593
Warrior Avatar asked Nov 05 '19 23:11

Warrior


2 Answers

Apple has answered our calls with iOS 15 and the newly introduced confirmationDialog API. ActionSheet has also been deprecated in this release.

ConfirmationDialog has been added as a view modifier and can be used on any view, very similar to the .actionSheet API we were using prior. When using the new dialog we can specify that the title is hidden and can use the Button API for role to control button appearance.

Below is an illustration of using it on a simple View.

struct ContentView: View {
    
    @State private var isShowingDialog: Bool = false
    
    var body: some View {
        VStack {
            Button {
                isShowingDialog = true
            } label: {
                Text("Tap Me")
            }
             .confirmationDialog("", isPresented: $isShowingDialog, titleVisibility: .hidden) {
                 Button("Normal") {
                 }
                 Button("Delete", role: .destructive) {
                 }
                 Button("Cancel", role: .cancel) {
                 }
            }
        }
    }
}

enter image description here

like image 128
Daniel Galasko Avatar answered Sep 18 '22 11:09

Daniel Galasko


The short answer is no. SwiftUI's current implementation will always make room for a title, and will only take Text views for its buttons.

It is unclear yet whether this is because Apple only had so much time before releasing SwiftUI this year, and wanted to tackle the simplest and most common use case, or whether they are taking a principled stance that ActionSheets should always have a standard look, including title and only text buttons. We'll have to wait and see.

like image 21
John M. Avatar answered Sep 19 '22 11:09

John M.