Search code examples
iosswiftuicollectionviewuicollectionviewcelldropdown

Dropdown list in UICollectionview cell


I am developing a TODOList(iOS application) but there is a problem i.e. how can I add dropdown list is uicollectionview cell. Means when view did load, collection view loaded, there should be a dropdown in every single cell


Solution

  • There's no any inbuilt dropdown functionality in iOS but you can do it by using UITableView or by using 3rd party library.

    I suggest you to try this. DropDown

    define this globally.

    let dropDown = DropDown()
    

    If you want to customise dropDown you can use this.

    func customizeDropDown() {
        DropDown.appearance().cellHeight = 40
        DropDown.appearance().backgroundColor = UIColor.white
        DropDown.appearance().selectionBackgroundColor = Colors.purpleColor
        DropDown.appearance().cornerRadius = 5
        DropDown.appearance().textColor = Colors.NavTitleColor
        DropDown.appearance().shadowColor = (UIColor.init(hexString: "1AD691")?.withAlphaComponent(0.0))!
        DropDown.appearance().shadowOpacity = 0.9
        DropDown.appearance().shadowRadius = 0
        DropDown.appearance().animationduration = 0.25
    }
    

    In cellForItemAt you need to add action on your dropdown button like this.

    cell.btnDropdown.tag = indexPath.item
    cell.btnDropdown.addTarget(self, action: #selector(btnDropDownTapped), for: .touchUpInside)
    

    Once you tapped on any button from UICollectionViewCell below method will call where you need to pass anchorView.

    @IBAction func btnDropDownTapped(_ sender: UIButton) {
        self.dropDown.anchorView = sender // The view to which the drop down will appear on
        self.dropDown.bottomOffset = CGPoint(x: 0, y: sender.bounds.height) //Top of drop down will be below the anchorView
    
        self.dropDown.dataSource = ["First", "Last", "Second", "Third"] // Static array you need to change as per your requirement
        self.dropDown.selectionAction = { [unowned self] (index, item) in
            print(item) // **NOTE: I AM JUST PRINTING DROPDOWN SELECTED VALUE HERE, YOU NEED TO GET `UICollectionViewCell` HERE YOU NEED TO SET VALUE INSIDE CELL LABEL OR YOU CAN SET SELECTED DROPDOWN VALUE IN YOUR MODEL AND RELOAD COLLECTIONVIEW**
    
            self.collectionView.reloadData()
        }
        self.dropDown.show()
    }
    

    If you have UITextField in your UICollectionViewCell then you can try this code inside textFieldShouldBeginEditing delegate.

    NOTE: I AM JUST PRINTING DROPDOWN SELECTED VALUE HERE, YOU NEED TO GET UICollectionViewCell HERE YOU NEED TO SET VALUE INSIDE CELL LABEL OR YOU CAN SET SELECTED DROPDOWN VALUE IN YOUR MODEL AND RELOAD COLLECTIONVIEW