Category

Multiselect UITableView with limited selections

Swift Language

Multiselect UITableView with limited selections

Simple example of creating a multi-select UITableView, but allow only a limited number of selected cells.

Introduction

Table of Contents

I wanted a multi-select table view but limit the number of selected cells. The “answers” on StackOverflow were quite awful – which is true > 50% of the time.

So here is a simple working example

How to

Table of Contents

Add a table view to your storyboard. (I know, well duh). In the attributes editor choose multi select.
Set your viewcontroller to be the table datasource and delegate. You know, the usual.

In your view controller, do the usual datasource setup.

For the limiting functionality, you need to do this in the delegate.

In my viewcontroller, I added a variable – the limit. Then in the delegate’s willSelectRowAtIndexPath func I compared the current number of selected cells (tableView.indexPathsForSelectedRows) to the limit returning nil if it’s over the limit.

That’s it. None of the contortions you see on SO.

In the other delegate methods, I just add eye candy.

Limited TableView Selection

And when you go over the limit.

Limited TableView Selection Alert

Summary

Table of Contents

All you really need to do is done in the delegate’s willSelectRowAtIndexPath func.

Resources

Table of Contents

2 thoughts on “Multiselect UITableView with limited selections”

  1. Hi, my name is Alok.
    I run you code this is perfectly run in your limited tableview example as project named.
    But when i implemented to my project it does not work correctly.
    Issue is: when i selecting a row the checkmark selected or appear. and if we again tap on different cell then the previous cell checkmark is disappered .
    what i do please tell.
    I already applied your copy paste code to my project but no fixed this issue.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.