swift 5 Как вызвать функцию по нажатии на кнопку

Существует функция WordsCard и для нее надо передать данные. Когда нажимается кнопка, должна вызваться функция

WordsCard(keyOfDictionaryLet: dictionary1Key, valueOfDictionaryLet: dictionary1Value)

Весь код:

class ViewController: UIViewController {
    
    func WordsCard(keyOfDictionaryLet : [String], valueOfDictionaryLet: [String]) {
        print("Hi")
        var keyOfDictionary = keyOfDictionaryLet
        var valueOfDictionary = valueOfDictionaryLet
        for i in 0..<buttonsMassive.count {
            buttonsMassive[i].isHidden = true
        }
        
        buttonWords.setTitle(keyOfDictionary[0], for: .normal)
        keyOfDictionary.remove(at: 0)
        
        
        
        buttonWords.frame.size = CGSize(width: buttonWordsWidth, height: buttonWordsHeight)
        buttonWords.layer.cornerRadius = CGFloat(roundf(Float(buttonsColumnSize / 10)))
        buttonWords.center = self.view.center
        view.addSubview(buttonWords)
        
    }
    
    var namesForButtonCollection : [String] = ["fruits", "city", "clock"]
    
    var countOfWordsForDictionary : [Int] = [4, 3, 2]
    
    var buttonWords = UIButton()
    
    
    let buttonsColumnSize : Int = Int(round(UIScreen.main.bounds.width / 2 - 30))
    let buttonsColumnPlace2 : Int = Int(round(UIScreen.main.bounds.width / 2 + 10))
    var buttonWordsWidth : Int = Int(round(UIScreen.main.bounds.width)) - Int(round(UIScreen.main.bounds.width/10))
    var buttonWordsHeight : Int = Int(round(UIScreen.main.bounds.height)) - Int(round(UIScreen.main.bounds.height/10))
    
    var buttonsMassive = [UIButton]()

    var buttonCount = true
    
    var dictionaryCollections : Dictionary = ["Apple":"Яблоко", "Grape":"Виноград", "Garnet":"Гранат", "Pear":"Груша", "Market":"Рынок", "House":"Дом", "Flat":"Квартира", "Ten":"Десять", "Clock":"Часы"]
    
    var dictionary1Key : [String] = []
    var dictionary1Value : [String] = []
    override func viewDidLoad() {
        super.viewDidLoad()
        buttonWords.isHidden = true
        var namesForButtonCollectionSecond : [String] = namesForButtonCollection
        
        
        createButtons()
        // access array mambers
    }
    
    private func createButtons() {
        
        
        
        var y = 50
        
        
        for i in 0..<namesForButtonCollection.count {
            var buttonCollectionFrame = CGRect(x: 20, y: y, width: buttonsColumnSize, height: buttonsColumnSize)
            var buttonCollectionFrame2 = CGRect(x: buttonsColumnPlace2, y: y, width: buttonsColumnSize, height: buttonsColumnSize)
            let button = UIButton(type: .system)
            if buttonCount {
                button.frame = buttonCollectionFrame
                buttonCount = false
            } else {
                button.frame = buttonCollectionFrame2
                buttonCount = true
                y += buttonsColumnSize + 20
            }
            button.backgroundColor = .gray
            button.titleLabel?.textAlignment = .center
            button.setTitle(namesForButtonCollection[0], for: .normal)
            namesForButtonCollection.remove(at: 0)
            button.layer.cornerRadius = CGFloat(roundf(Float(buttonsColumnSize / 10)))
            for i in 0..<countOfWordsForDictionary[0] {
                for (key, value) in dictionaryCollections {
                    dictionary1Key.append(key)
                    dictionary1Value.append(value)
                }
            }
            
            
            view.addSubview(button)
            buttonsMassive.append(button)
            
            }
            
            
        }
        
    }

Ответы (1 шт):

Автор решения: schmidt9

На примере моего предыдущего ответа - используем метод UIButton.addTarget, получаем индекс кнопки и по этому индексу можно получать данные из массива с данными например

class ViewController: UIViewController {
    
    let buttonsColumnSize = Int(round(UIScreen.main.bounds.width / 2 - 30))
    
    var buttons = [UIButton]()

    override func viewDidLoad() {
        super.viewDidLoad()
        createButtons()
        // access array mambers
        buttons[1].setTitle("other title", for: .normal)
    }
    
    @objc func showWordsCard(_ sender: UIButton) {
        let index = buttons.firstIndex(of: sender)!
        // do something with index
    }
    
    private func createButtons() {
        
        var y = 50
        
        for i in 0..<5 {
            let button = UIButton(type: .system)
            button.frame = CGRect(x: 20, y: y, width: buttonsColumnSize, height: buttonsColumnSize)
            button.titleLabel?.textAlignment = .center
            button.setTitle("Button \(i)", for: .normal)
            button.addTarget(self, action: #selector(showWordsCard(_ :)), for: .touchUpInside)
            // other setup ...
            view.addSubview(button)
            buttons.append(button)
            
            y += buttonsColumnSize + 50
        }
    }

}
→ Ссылка