11.6. Adding Accessory Button to Table View (Edit/Delete a Contact)

Adding a Button to the TableView Cell as an Accessory

UITableView allows us to add views as accessories. Adding an accessory view is the easiest way to enable user interactions with a cell in a table view. So, in our app, we want to do the following:

  • We will have a settings button. If the user taps on the button, there will be a menu to give the user two options: Edit and Delete.

  • The user can select one of the options to either edit or delete the contact.

Let's open ViewController.swift file. Go to where we adopt the protocols related to the table view. Then go to the adopted method for cellForRowAt, where we initialize the cell.

Add the following code to add an accessory button:

In the above code:

  • We create a system button called buttonOptions. We set the buttonOptions to sizeToFit(). It means we ask the button to size to fit the cell's width.

  • Then we set the settings to show the menu as the primary action on tapping the button.

  • Then we set the image for the button from an appropriate icon from SF Symbols.

  • Then from line 13 through 21, we setup the menu.

  • Finally, in line 23, we set the cell's accessory view to the button.

If you noticed, the accessory view is a UIView. So technically, you can design your custom view with multiple UI elements. You can add multiple buttons if you want to. For the buttons, you must work with proper constraints, height, width, etc. (And it is a little complicated).

Writing methods when the user selects an option

We need to write the methods for enabling the actions when the user selects an option from the menu (edit/delete). We write them in the ViewController class.

Now, let's run the app:

See? They are printing the appropriate logs as outputs. You can now do anything to edit or delete the contact.

Last updated

Was this helpful?