Как вызвать действие кнопки для каждой ячейки в SecondVC после выбора ячейки в FirstVC? - PullRequest
0 голосов
/ 13 мая 2019

У меня есть два контроллера представления с двумя различными представлениями таблицы, где FirstVC отправляет данные на SecondVC с помощью segue.У меня есть данные из файла JSON, и все работает отлично.У меня есть кнопка в SecondVC (называемая likeButton) , которую я хочу, когда при нажатии отображается «похожее изображение» и при повторном нажатии возвращается к обычному изображению «не нравится».Я добился этого и отлично работает.Также отправляет данные обратно в FirstVC, где отображается, что изображение «как». Я использовал UserDefaults. Моя проблема заключается в том, что когда вы нажимаете кнопку, чтобы отобразить «как изображение» в SecondVC внутри likeButtonAction (_ sender: UIButton) функция, которая нажимается в каждой ячейке. Мне нужно выбрать для этой конкретной ячейки. Я все еще новичок в Xcode. Любая помощь будет высоко ценится. Спасибо

Вот что у меня есть: Контроллер первого вида

import UIKit

class FirstVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
    let defaults = UserDefaults.standard

    @IBOutlet weak var tableView: UITableView

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "popDetails" {
            guard let vc = segue.destination as? DetailsViewController,
                let index = tableView.indexPathForSelectedRow?.row
            else {
                return
            }

            vc.cocktailsName = drinks[index].cocktailName
            // more data send
        }
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return drinks.count
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        tableView.rowHeight = 260

        let cell = tableView.dequeueReusableCell(withIdentifier: "favoriteCell") as! TableViewCell

        cell.cocktailLabel.text = drinks[indexPath.row].cocktailName

        selectedValue = defaults.value(forKey: "myKey") as! String

        if selectedValue == "true" {
            cell.heartImage.image = UIImage(named: "heart")
        } else if selectedValue == "false" {
            cell.heartImage.image = UIImage(named: "transparent")
        }

        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        DispatchQueue.main.async {
            self.performSegue(withIdentifier: "popDetails", sender: self)
        }
    }
}

Контроллер второго вида:

var selectedValue = String()

class SecondVC: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextViewDelegate {
    var cocktailsName: String!

    @IBOutlet weak var tableView: UITableView!

    var mainCocktails: Cocktails!
    var tap = UITapGestureRecognizer()
    var defaults = UserDefaults.standard
    var checked = false

    @IBAction func done(_ sender: AnyObject) {
        dismiss(animated: true, completion: nil)
    }

    @IBAction func likeButtonAction(_ sender: UIButton) {
        if checked {
            sender.setImage(UIImage(named:"likeButton"), for: UIControl.State.normal)
            checked = false
        } else {
            sender.setImage(UIImage(named:"likeButtonOver"), for: UIControl.State.normal)
            checked = true
        }

        selectedValue = String(checked)
        defaults = UserDefaults.standard
        defaults.set(selectedValue, forKey: "myKey")
        defaults.synchronize()
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "buttonsCell") as! MainPictureViewCell

        cell.nameLabel.text = cocktailsName
        selectedValue = self.defaults.value(forKey: "myKey") as! String

        if selectedValue == "true" {
            cell.likeButton.setImage(UIImage(named: "likeButtonOver"), for: .normal)
        } else if selectedValue == "false" {
            cell.likeButton.setImage(UIImage(named: "likeButton"), for: .normal)
        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 4
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
}

1 Ответ

0 голосов
/ 14 мая 2019

Вы и поместите кнопку в ячейку и сделаете розетку в cellController. Затем вам нужно добавить цель для кнопки в cellForRowAt и предоставить тег indexpath.row для кнопки

extension ViewController: UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 10
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "TableCell") as! TableCell
    cell.button.addTarget(self, action: #selector(buttonPressed), for: .touchUpInside)
    cell.button.tag = indexPath.row
    return cell
}

}

//MARK:- Handel  Button
@objc func buttonPressed(sender:UIButton){
    print(sender.tag)

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...