SwiftUI board: Methods to create a context menu beneath iOS 13

Beforehand, Apple had formally launched iOS 13 to the general public. Along with the darkish mode and different new options, the newest model of iOS additionally introduces us a brand new technique referred to as context menu to work together with the system.

A popup menu is much like Peek and Pop in 3D Contact. A notable distinction is that this function works on all gadgets operating iOS 13 and later, even when the system doesn’t help 3D Contact. To convey up a context menu, folks use the contact and gesture held if the system is powered with 3D Contact.

Should you upgraded to iOS 13, you could find this new management in most saved functions reminiscent of Maps and Photographs.

On this tutorial, let's see the right way to implement the context menu in SwiftUI.

Word: To make use of this tutorial, you have to have Xcode 11 and macOS Catalina (v10.15).

Create a context menu in SwiftUI

To get began, please obtain this startup venture and unzip it to your Mac. After you open the SwiftUIList.xcodeproj file, run the venture or preview it within the workspace. The applying ought to present you a listing of eating places.

Editor's Word : Should you're new to SwiftUI and also you have no idea the right way to current a listing, take a look at our SwiftUI tutorial for newcomers.

What we’re going to do is create a context for this demo utility. We wish to set off the context menu when folks contact and maintain one of many traces. Within the menu, customers have the selection between two motion buttons: Delete and Favourite. When this selection is chosen, the Delete button removes the road from the listing. The Favourite button will mark the chosen line with a star indicator.

Utilizing the context menu modifier

SwiftUI made it very simple to implement a context menu. You simply connect the contextMenu container to a view and configure its menu objects.

To current these two components within the contextual menu, we are able to affiliate the contextMenu with every of the traces of the listing, as follows:

Itemizing {
ForEach (eating places) {restaurant in
BasicImageRow (restaurant: restaurant)
.Contextual menu

Button (motion:
// delete the chosen restaurant
)
HStack
Textual content ("Delete")
Picture (systemName: "trash")

Button (motion:
// mark the chosen restaurant as a favourite
)
HStack
Textual content ("Favourite")
Picture (systemName: "star")

}
}

1

2

three

four

three

eight

9

10

11

12

10

[1945900]]

[1945900]] [1945900]] 15

16

17

18

19

20

21

22

23

24

25

Listing {

[1945910] [1945908] Eating places ) { ] In Advance

BasicImageRow From the Restaurant : )

. [1945913]

Button