Code Monkey home page Code Monkey logo

rsselectionmenu's Introduction

RSSelectionMenu

An elegant selection list or dropdown menu for iOS with single or multiple selections.

https://github.com/rushisangani/RSSelectionMenu/blob/master/Images/multi1.gif

Demo Video

Features

  • Single and Multiple selection.
  • Show menu with presentation styles like Present, Push, Popover, Formsheet, Alert, Actionsheet
  • Set UITableViewCell types like Basic, Subtitle, Right Detail
  • Set UITableViewCell selection style Tickmark or Checkbox
  • Search Items from the list
  • Works with Custom UITableViewCells
  • Works with Custom model classes and structs
  • Set Maximum selection limit
  • Provide Empty data set text
  • Provide header row as Empty, All, None or Custom Text
  • Customizable design for UINavigationBar and UISearchBar

What's new in 7.1.3

  • Popover Style Improvements
  • Now you can specify UITableView.Style while initializing

Already using? Migrate to 7.1.3

  • Remove all references of UniquePropertyDelegate, uniquePropertyName, and getUniquePropertyName()
  • Conform to Equatable in your model classes (if required)

Requirements

iOS 9.0+ | Xcode 8.3+ | Swift 3.0+

Installation

CocoaPods

pod 'RSSelectionMenu' or pod 'RSSelectionMenu', '~> 7.1.3'

Carthage

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.

You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

To integrate RSSelectionMenu into your Xcode project using Carthage, specify it in your Cartfile:

github "rushisangani/RSSelectionMenu" ~> 7.1

Then follow below steps:

  • Run carthage update to build the framework.
  • Set Framework search path in target build settings : Build Settings -> Framework Search Paths : $(PROJECT_DIR)/Carthage/Build/iOS
  • Add RSSelectionMenu.framework in Embedded Binaries.
  • Add RSSelectionMenu.framework in Linked Frameworks and Libraries.

Usage

Simple Selection List

let simpleDataArray = ["Sachin", "Rahul", "Saurav", "Virat", "Suresh", "Ravindra", "Chris"]
var simpleSelectedArray = [String]()

// Show menu with datasource array - Default SelectionStyle = single
// Here you'll get cell configuration where you'll get array item for each index
// Cell configuration following parameters.
// 1. UITableViewCell   2. Item of type T   3. IndexPath

let selectionMenu = RSSelectionMenu(dataSource: simpleDataArray) { (cell, item, indexPath) in
    cell.textLabel?.text = item
}

// set default selected items when menu present on screen.
// here you'll get handler each time you select a row
// 1. Selected Item  2. Index of Selected Item  3. Selected or Deselected  4. All Selected Items

selectionMenu.setSelectedItems(items: simpleSelectedArray) { [weak self] (item, index, isSelected, selectedItems) in

    // update your existing array with updated selected items, so when menu show menu next time, updated items will be default selected.
    self?.simpleSelectedArray = selectedItems
}

// show as PresentationStyle = push
selectionMenu.show(style: .push, from: self)

Multiple Selection List

let selectionMenu = RSSelectionMenu(selectionStyle: .multiple, dataSource: simpleDataArray) { (cell, name, indexPath) in

    cell.textLabel?.text = name

    // customization
    // set image
    cell.imageView?.image = #imageLiteral(resourceName: "profile")
    cell.tintColor = #colorLiteral(red: 0.2745098174, green: 0.4862745106, blue: 0.1411764771, alpha: 1)
}
  • Set Maximum selection limit (Optional)
selectionMenu.setSelectedItems(items: selectedDataArray, maxSelected: 3) { (item, selected, selectedItems) in
}
// or 
selectionMenu.maxSelectionLimit = 3

Cell Selection Style

selectionMenu.cellSelectionStyle = .tickmark
// or
selectionMenu.cellSelectionStyle = .checkbox

Presentation Style - Formsheet, Popover, Alert, Actionsheet

// show as formSheet
selectionMenu.show(style: .formSheet, from: self)


// show as popover
selectionMenu.show(style: .popover(sourceView: sourceView, size: nil), from: self) 

// or specify popover size
selectionMenu.show(style: .popover(sourceView: sender, size: CGSize(width: 200, height: 300)), from: self)


// show as alert
selectionMenu.show(style: .alert(title: "Select", action: nil, height: nil), from: self)

// or specify alert button title
selectionMenu.show(style: .alert(title: "Select", action: "Done", height: nil), from: self)


// show as actionsheet
selectionMenu.show(style: .actionSheet(title: nil, action: "Done", height: nil), from: self)

Auto Dismissal

Prevent auto dismissal for single selection

selectionMenu.dismissAutomatically = false

Event Handlers

On Dismiss

selectionMenu.onDismiss = { [weak self] selectedItems in
    self?.selectedDataArray = selectedItems
    
    // perform any operation once you get selected items
}

On WillAppear

selectionMenu.onWillAppear = {
    /// do something..
}

Customization

SearchBar

  • You'll get notified via handler, when user starts typing in searchbar.
// show searchbar
selectionMenu.showSearchBar { [weak self] (searchText) -> ([String]) in

  // return filtered array based on any condition
  // here let's return array where name starts with specified search text

  return self?.dataArray.filter({ $0.lowercased().hasPrefix(searchText.lowercased()) }) ?? []
}

Cell Style - Right Detail or Sub Title

let selectionMenu = RSSelectionMenu(selectionType: .single, dataSource: dataArray, cellType: .rightDetail) { (cell, item, indexPath) in

    // here you can set any text from object
    // let's set firstname in title and lastname as right detail

    let firstName = item(separatedBy: " ").first
    let lastName = item.components(separatedBy: " ").last

    cell.textLabel?.text = firstName
    cell.detailTextLabel?.text = lastName
}

selectionMenu.setSelectedItems(items: selectedDataArray) { [weak self] (item, selected, selectedItems) in
    self?.selectedDataArray = selectedItems
}

// show as default
selectionMenu.show(from: self)

Custom Cells

  • Provide custom cell with xib file name and cell identifier.
let cellNibName = "CustomTableViewCell"
let cellIdentifier = "cell"

// create menu with multi selection and custom cell

let selectionMenu =  RSSelectionMenu(selectionStyle: .multiple, dataSource: customDataArray, cellType: .custom(nibName: cellNibName, cellIdentifier: cellIdentifier)) { (cell, person, indexPath) in

    // cast cell to your custom cell type
    let customCell = cell as! CustomTableViewCell

    // here you'll get specified model object
    // set data based on your need
    customCell.setData(person)
}

Header Row - Empty, None, All, or Custom

// To show first row as Empty, when dropdown as no value selected by default
// add first row as empty -> Allow empty selection

let isEmpty = (selectedDataArray.count == 0)
selectionMenu.addFirstRowAs(rowType: .empty, showSelected: isEmpty) { (text, selected) in

    /// do some stuff...
    if selected {
        print("Empty Option Selected")
    }
}

Empty Data String

// show message 'No data found'
menu.showEmptyDataLabel()

// or
menu.showEmptyDataLabel(text: "No players found")

DataSource - Equatable conformance

struct Employee: Equatable {
    
    let empId: Int?
    let name: String?
}

or

class Person: NSObject {

    let id: Int
    let firstName: String
    let lastName: String

    init(id: Int, firstName: String, lastName: String) {
        self.id = id
        self.firstName = firstName
        self.lastName = lastName
    }
}

UI Customization

NavigationBar

  • Set Title, BarButton Titles, TintColor, and Title Color
// set navigation bar title and attributes
selectionMenu.setNavigationBar(title: "Select Player", attributes: [NSAttributedString.Key.foregroundColor: UIColor.white], barTintColor: #colorLiteral(red: 0.1019607857, green: 0.2784313858, blue: 0.400000006, alpha: 1), tintColor: UIColor.white)

// right barbutton title - Default is 'Done'
selectionMenu.rightBarButtonTitle = "Submit"

// left barbutton title - Default is 'Cancel'
selectionMenu.leftBarButtonTitle = "Close"

SearchBar

  • Set Placeholder, Tint Color
// show searchbar with placeholder and barTintColor
selectionMenu.showSearchBar(withPlaceHolder: "Search Player", barTintColor: UIColor.lightGray.withAlphaComponent(0.2)) { [weak self] (searchText) -> ([String]) in

    return self?.dataArray.filter({ $0.lowercased().starts(with: searchText.lowercased()) }) ?? []
}

Example

See Example for more details.

License

RSSelectionMenu is released under the MIT license. See LICENSE for details.

rsselectionmenu's People

Contributors

amirnajafi avatar andrewgable avatar prscx avatar roulljdh avatar rursache avatar rushisangani avatar sagargondaliya avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rsselectionmenu's Issues

automaticDimension error after updating to 5.3

Hi
I'm getting error Error:(78, 33) 'automaticDimension' has been renamed to 'UITableViewAutomaticDimension' while compiling my app after I updated to 5.3
Can you please look into it?

Diss select an item

Hi,

I have a list of products with single selection. If the user regret of the product I can't diss select. How can you do that.

Formsheet height incorrect after 5.1.1 update

I was using RSSelectionMenu with Formsheet style fine with version 5.0, after updating to 5.1.1 Formsheet height goes to the bottom of the screen.

New Actionsheet and Alert styles work ok.

tableview height

tableview height should calculate dynamic if I have just 2 row your library create table view with lots of empty white space

Every row mark as checked

What is my problem? - It's works perfect but when I select one row, the App shows me "one row selected... etc" and it's okay, but when im looking into an App I have "checked" every rows.

there is my code:

@IBAction func licenseSelection(_ sender: Any) {
                let context = licenseSavingController.persistentContainer.viewContext
                let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Licencja")
            let selectionMenu = RSSelectionMenu(selectionType: .Single, dataSource: licencje, cellType: .Basic) { (cell, object, indexPath) in
                cell.tintColor = .orange

                request.returnsObjectsAsFaults = false
                do {
                    var result = try context.fetch(request) as! [NSManagedObject]
                    result = [result[indexPath.row]]
                    for data in result {
                        self.licznik = self.licznik+1
                        cell.textLabel?.text = data.value(forKey: "licenseDescript") as? String ?? data.value(forKey: "licenseURL") as? String
                        //forKey: "licenseURL") as? String ?? "default"
                        //forKey: "licenseNumber") as? String ?? "default"
                        //data.value(forKey: "deviceID") as? String ?? "default"
                    }
                } catch {
                    print("Failed")
            }
        }

            selectionMenu.uniquePropertyName = "licznik"
            selectionMenu.setSelectedItems(items: wybranaLicencja) { (text, isSelected, selectedItems) in
                self.wybranaLicencja = selectedItems
                print(selectedItems)
            }
            selectionMenu.show(style: .Popover(sourceView: sender as! UIView, size: nil), from: self)
        }

like that: https://imgur.com/nveTKJ8 Im really confused with this :P

Empty tableView message

I would like to show a UILabel with a message when the datasource is empty to handle empty tableView. How is it possible here?

Formsheet looks really bad in landscape mode

In landscape mode there's too much padding on top and bottom sides, so it just shows a single item.

Please fix it so more items are shown and hopefully even make it device independent, so the bigger the screen, the more items it shows.

Thanks in advance.

captura de pantalla 2018-07-28 a la s 21 42 59

Get the Id of the cell Selected?

Thanks for the great library.
How to get the id of the selected cell in formsheet?
The dataSource is a dictionary of key, value pairs. On cell selection how to capture the Id ?
Any help?
Thanks.

Selection issues in v 5.1

Hey

After updating to latest version, I'm facing an issue where selection of some items in table does not work.

It's happening in Single and Multiple selection types as well. And without custom cells too.

Here's a gif showing the issue:

kapture 2018-08-21 at 11 47 27

cancell button

first i want to thanks for your very good support
thanks to add function to add title but very little thing still has problem for me
when i add search button i can change the placeholder of search that is awesome but there is a
cancell buttun with text "Cancell" its whould be nice if you can add this function to

by the way you are so cool man !!!

Install on IOS 9.0

I installed the zip on IOS 9.0 and all seemed fine. Is there a reason the deployment target in the podfile is 10.0? Thanks!

Filter not working properly

Hi,

I'm using custom model with custom cell

This is the class "bank" :

class bank: NSObject, UniqueProperty {
    
    let banknm:String
    
    init(banknm:String) {
        
        self.banknm = banknm
    }
    
    // Here id has the unique value for each person
    func uniquePropertyName() -> String {
        return "banknm"
    }
}

And this the function I'm calling on Button Click.

func displayBank() {
        
        let selectionMenu =  RSSelectionMenu(selectionType: .Single, dataSource: bankDataArray, cellType: .Custom(nibName: "CustomTableViewCell", cellIdentifier: "customCell")) { (cell, bank, indexPath) in
            
            let customCell = cell as! CustomTableViewCell
            
            let rec   = self.bankDataArray[indexPath.item]
            customCell.lbl.text = rec.banknm
        }
        selectionMenu.setSelectedItems(items: selbankDataArray) { (text, selected, selectedItems) in
            self.selbankDataArray = selectedItems
            
            self.btnBank.setTitle(self.selbankDataArray.first?.banknm, for: .normal)
            
        }
        if(bankDataArray.isEmpty) {
            selectionMenu.addFirstRowAs(rowType: .Custom(value: "No Banks Found"), showSelected: self.firstRowSelected) { (text, isSelected) in
                
                // update your flag here to maintain consistency. -  This is required to be update when presenting for the second time.
                self.firstRowSelected = isSelected
            }
        }
                
        selectionMenu.showSearchBar { (searchtext) -> ([bank]) in
            return            self.bankDataArray.filter({$0.banknm.lowercased().hasPrefix(searchtext.lowercased())
                
                
            })
        }
        
        selectionMenu.show(from: self)
    }

Now when I type to filter the list, It's not returning the right ones
Here's the screen recording...
https://drive.google.com/open?id=1JCWdYm4NI9nuf8q3wvD3zaw4x3btFZYq

Build error

Building project takes too long time when adding the pod of RSSelectionMenu

Cannot assign value type of...

Hi, I've recently added your lib to my project but I'm getting this error

Cannot assign value of type '[String : Any]?' to type '[NSAttributedStringKey : Any]?'

This error can be found in the file RSSelectionMenuController.swift line 325 witch contains this function

    // navigation bar
    fileprivate func setNavigationBarTheme(_ theme: NavigationBarTheme) {
        if let navigationBar = self.navigationController?.navigationBar {
            
            navigationBar.barTintColor = theme.color
            if theme.color != nil {
                navigationBar.tintColor = UIColor.white
            }
            
            navigationItem.title = theme.title
            navigationBar.titleTextAttributes = theme.attributes // <- Line where the error is located (325)
        }
    }

Missing selected items when using the select all first first row option

Hi,

Again I am loving this pod. Thanks for keeping it well maintained!!

I think I found a bug today.

If you add a first row with type .All. In the callback to setSelectedItem. The selected items array is returning with zero items.

It would make sense to me if there is a select all option available the setSelectedItem closure should return an array of all the items.

If this is not a bug and it is the intentional behaviour I am sorry. I just thought I would raise it with you.

Thanks.

Using Present or Push disables the custom NavigationBar styles

I want to use .Multiple and .Present at the same time. I do not want the "Done" button but a cancel button on the left. Anyways, the library keeps overriding my custom configuration.

Please give us full control of the NavigationBar buttons in any of the styles.
Basically, disable these checks, please.

Thanks

Disable cell check

Hi,

I want to disable checking the default checked cell so that user cannot uncheck them.
How can I do that please?

Thank you

[Feature Request] Add an option to show a simple title in Formsheet style

Hello

Thanks for this awesome lib. Works great. Anyways, I was wondering if you could allow showing a simple title at the top of the selection menu when its style is .Formsheet, basically above the search bar (if it's enabled) or where the search bar would be

Thanks in advance ๐Ÿ˜€๐Ÿ™Œ๐Ÿผ

Issue in Formsheet

Formsheet appears only one time, If the tap anywhere else or make a selection and then try to show the Formsheet it shows nothing.

How find index selected

If I select an item how can I know the index that I select, in the selectionMenu.setSelectedItems(items: [])

thanks

[BUG] When selected a item shows multiple selections

Hi, I'm using your plugin as a popover selection list.
Currently I'm loading the items from the CoreData so I extended the class I needed to get an identifier as specified in the documentation

extension CategoriesCoreData: UniqueProperty {
    public func uniquePropertyName() -> String {
        return "title"
    }
}

The title is for sure unique because before adding a new category the software checks if that title already exists
When I tap, in this case a category, they show all as selected UI only, with this I mean, on the UI appears that all have been selected but on the code only one was selected as it should.
captura de ecra 2018-07-20 as 00 05 22

Get data from Api via closure

How to pass data through api return. For eg: With every searchText i call an api which return data array and then it refreshes the selection menu. When i try to add the api inside the return function. It shows an error that closure require a return. It is not considering the return from the closure as a return.
For eg:

 selectionMenu.showSearchBar(withPlaceHolder: "Search Player", tintColor: UIColor.white.withAlphaComponent(0.3)) { (searchText) -> ([SearchModel]) in


            let parameters = ["term": searchText]
            ThreadStore.shared.search(parameters: parameters) {(success, list) in
               return list as! [SearchModel] .   //(Returning the response from the web service)
           }
        }

Clear Selection Button

Hi,

this is a really great swift module!

Is it possible to have a button e.g. on the left navbar for clearing the selection?

Thanks
Phil

what is correct version to install ?

when i added pod 'RSSelectionMenu' into my podfile i got following message in terminal

Installing RSSelectionMenu (3.3)
which means it is installing 3.3

and when i addedd pod 'RSSelectionMenu', '~> 5.2.1' into podfile i got following message in terminal

CocoaPods could not find compatible versions for pod "RSSelectionMenu":
  In Podfile:
    RSSelectionMenu (~> 5.2.1)

None of your spec sources contain a spec satisfying the dependency: `RSSelectionMenu (~> 5.2.1)`.

Please define which is correct version to install.

error in buttuns

i don't know why in new update my buttons (navigations button and search cancel button ) not showing up at all
in my code i setup

selectionMenu.rightBarButtonTitle = "Submit"
selectionMenu.leftBarButtonTitle = "Close"

and for my search i setup
selectionMenu.searchBarCancelButtonAttributes = SearchBarCancelButtonAttributes("Dismiss", .red)

and i want to customize search placeholder alignment in my case its stick on right but my language is RTL
screen shot 1396-08-06 at 12 05 46 pm

thank you for your support

Default Selection

Thank for library.
How to set item default selected in single selection?

NavigationBar barTintColor not always working

Hi

I am trying to set #212121 as the barTintColor of the NavigationBar but it isn't working properly as a lighter color is set.

Look at the screenshot below: the StatusBar color and SearchBar colors are #212121 but the NavigationBar's isn't (which actually is #323232).

captura de pantalla 2018-08-18 a la s 18 06 43

On dismiss closure feature request

Hey

This pod is so so good and such a pleasure to use. Thanks for making and sharing it!

I have a feature request. Would it be possible to add an on dismiss callback closure which would be triggered when the formsheet style gets dismissed.

Thanks!

Popover with Title

Hi folks
Is there a way to show "Popover" with a NavigationBar or at least a custom Title?
I saw the screenshot in this ticket: #51
This would be exactly what I need.

Bests

Philippe

Error while creating menu

let selectionMenu = RSSelectionMenu(dataSource: simpleDataArray) { (cell, object, indexPath) in
cell.textLabel?.text = object
}

When I try to create a menu using code above, compiler give this error:

image

Sticky Search bar

Thanks for such a great library, Can you please make the search bar as sticky on top while scrolling, it will possible by adding searchbar in tableview delegate , 'tableView(_ tableView: UITableView,
viewForHeaderInSection section: Int) -> UIView?' instead of 'tableHeaderView',
Thanks for great work ๐Ÿ’ฏ ๐Ÿ‘

Formsheet Width is not proper some time

I am using formsheet to present users list which works fine but some time the width of formsheet shrink check the following image.
screen shot

It happens only some time other time the width is fine but i am unable to find why this is happening.
img_0070

onDismiss was not found

Hi

Awesome work with RSSelectionMenu. Makes creating of drop down easier, manageable, and cool. Though I am encountering an issue when I try to use onDismiss. Swift shows an error that the menu has no member 'onDismiss'. Is there some import or configuration I am missing?

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.