Search code examples
swiftxcodeswift3storyboardiboutlet

Swift3 Multiple buttons dynamic coding to trigger event


I have multiple buttons. Each button contains a language label.

I want to make it so that when users tap on the button, the selected language label changes its value according to the button tapped.

The selected language outlet is called SelectedLangText.

A simple solution would be to create multiple Action outlets for each button and set the value of SelectedLangText label. However, if there would be 100 buttons, that would be bad coding.

I'm not sure how to approach this situation in Swift 3 coming from web development.

enter image description here


Solution

  • I prefer using the delegate design pattern when it comes to solving an issue like that for it I find it to be a much cleaner approach than just a mass amount of @IBActions

    1- Create a Language class import Foundation

    class Language {
        var id: Int
        var name: String
        init(id: Int, name: String) {
            self.id = id
            self.name = name
        }
    }
    

    2- Create the custom cell in the storyboard or nib and then add the appropriate outlets and actions. And then you create a Delegate protocol for it

    import UIKit
    protocol CustomCellDelegate: class {
        func customCell(newLanguageSelected language: Language)
    }
    class CustomCell: UITableViewCell {
        var language: Language!
        @IBOutlet weak var languageTextLabel: UILabel!
        weak var delegate: CustomCellDelegate?
        func setupCustomCell(withLanguage language: Language){
            self.language = language
            self.languageTextLabel.text = self.language.name
        }
        @IBAction func buttonPressed(sender: UIButton){
            delegate?.customCell(newLanguageSelected: self.language)
        }
    }
    

    3- Finally add the implementation in the cellForRow method of the UITableViewDataSource and add the implementation of the delegate in the UITableViewController class

    import UIKit
    class YourTableViewController: UITableViewController{
        var languages: [Language] = []
    
        //implement the other methods in the dataSource
    
        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "reuse", for: indexPath) as! CustomCell
            cell.delegate = self
            cell.setupCustomCell(withLanguage: languages[indexPath.row])
            return cell
        }
    }
    extension YourTableViewController: CustomCellDelegate{
        func customCell(newLanguageSelected language: Language) {
            //Do what you will with the language
        }
    }
    

    Good luck