首页 > 解决方案 > Swift:使用 tableView DidSelect 方法更改单元格的 UIButton 图像

问题描述

我有TableView两个标签和一个UIButton在 Tableview 内。所以在DidSelect方法上我想改变UIButton那个特定单元格的图像。作为附加图像。

在此处输入图像描述

标签: swiftxcodeuitableviewuibutton

解决方案


检查这个

在此处输入图像描述

import UIKit

class ButtonTblViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {

    var arry = ["Montitanki Chowk","Greenland Chokdi"]
    var SelectData = [NSMutableDictionary]()

    @IBOutlet weak var tbleVw: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        for i in 0..<arry.count
        {
            self.SelectData.append(["data":arry[i],"isSelect":"NO"])
        }

        self.tbleVw.reloadData()
        // Do any additional setup after loading the view.
    }

    // MARK - tableView Delegates

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:listTble = tableView.dequeueReusableCell(withIdentifier: "CellID", for: indexPath as IndexPath) as! listTble
        cell.lblTit.text =  self.SelectData[indexPath.row].value(forKey: "data") as? String

        cell.btnRdo.tag = indexPath.row
        let tapgesture = UITapGestureRecognizer(target: self , action: #selector(self.sectionTapped(_:)))
        cell.btnRdo.addGestureRecognizer(tapgesture)

        let selData = self.SelectData[indexPath.row].value(forKey: "isSelect") as! NSString

        if selData == "NO" {
            cell.btnRdo.setImage( UIImage(named: "btnUnSel"), for: .normal)
        } else {
            cell.btnRdo.setImage( UIImage(named: "btnSel"), for: .normal)
        }

        return cell
    }

    @objc func sectionTapped(_ sender: UITapGestureRecognizer){
        if(self.SelectData[(sender.view?.tag)!].value(forKey: "isSelect") as! String == "NO"){
            self.SelectData[(sender.view?.tag)!].setValue("YES", forKey: "isSelect")
        }else{
            self.SelectData[(sender.view?.tag)!].setValue("NO", forKey: "isSelect")
        }
        self.tbleVw.reloadData()
    }

    /*
     // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

class listTble: UITableViewCell {
    @IBOutlet weak var lblTit: UILabel!
    @IBOutlet weak var btnRdo: UIButton!
}

输出

在此处输入图像描述


推荐阅读