简体   繁体   中英

How to call button action for each cell in SecondVC after selecting cell in FirstVC?

I have two view controllers with two different table views where the FirstVC sends data to the SecondVC with segue. I have the data coming from a json file and everything works fine. I have a button in the SecondVC (called likeButton) that I want when is pressed to show a 'like image' and pressed again goes back to normal image 'not like'. I achieved that and works fine. Also sends the data back to the the FirstVC where is displayed that the image is "like'. I used UserDefaults. My problem is that when you press the button to display the 'like image' in the SecondVC inside likeButtonAction(_ sender: UIButton) function it gets pressed in every cell. I need to be selected for that particular cell. I am still new to Xcode. Any help will be much appreciated. Thanks

This is what I have: First View Controller

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)
        }
    }
}

Second View Controller:

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
    }
}

You and place button in cell and make outlet in cellController. Then you have to add target to button in cellForRowAt and provide the tag of indexpath.row to button

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)

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM