繁体   English   中英

通过点击表格视图中的单元格来检查/取消选中该复选框,以及如何知道已选中或取消选中的单元格

[英]check / uncheck the check box by tapping the cell in table view and how to know which cell has checked or unchecked

我是ios swift 2.2的新手。 我尝试使用自定义单元格xib创建一个表视图。 我在表格视图中填充了一些数据。 我还添加了一个自定义复选框按钮。 我正在为该复选框按钮创建单独的类。 现在当我点击我的customcell.xib中的按钮时。但是当我点击我的单元格时,我的复选框没有改变。 我需要两者兼得。 当我点击我的按钮时,它应该更改为选中并取消选中图像。 当我点击我的单元格时,我还需要更改我的按钮以选中或取消选中图像

当我向下滚动并再次回到顶部时,我检查的图像会自动切换到正常检查框。

我需要做一些动作,所以为此。 当我点击任何单元格时,我的复选框应该检查并取消选中。而且我需要知道哪个行单元格已经检查过图像。 这样我就可以单独对我选中的图像行单元格执行某些操作。

这是我的自定义复选框类:

import UIKit

class CheckBoxButton: UIButton {

    // Images
    let checkedImage = UIImage(named: "CheckBoxChecked")! as UIImage
    let uncheckedImage = UIImage(named: "CheckBoxUnChecked")! as UIImage

    // Bool property
    var isChecked: Bool = false {
        didSet{
            if isChecked == true {
                self.setImage(checkedImage, forState: .Normal)
            } else {
                self.setImage(uncheckedImage, forState: .Normal)
            }
        }
    }

    override func awakeFromNib() {
        self.addTarget(self, action: #selector(CheckBoxButton.buttonClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside)
        self.isChecked = false
    }

    func buttonClicked(sender: UIButton) {
        if sender == self {
            if isChecked == true {
                isChecked = false
            } else {
                isChecked = true
            }
        }
    }

}

Cutom cell.xib类:

import UIKit

class FavCell: UITableViewCell {

    @IBOutlet weak var FLabel1: UILabel!
    @IBOutlet weak var FLabel2: UILabel!

    @IBOutlet weak var checkbox: CheckBoxButton!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }



    @IBAction func checkboxpress(sender: AnyObject) {
    }



}

我的viewcontroller.swift

import UIKit

class FavVC: UIViewController {

    @IBOutlet weak var FavTableView: UITableView!

    //var FData = [FavouritesData]()

    var arrDict :NSMutableArray=[]

    let cellSpacingHeight: CGFloat = 5  // cell spacing from each cell in table view

    override func viewDidLoad() {

        super.viewDidLoad()

        self.jsonParsingFromURL()

        let nib = UINib(nibName:"FavCell", bundle: nil)

        FavTableView.registerNib(nib, forCellReuseIdentifier: "FCell")

    }
// web services method
    func jsonParsingFromURL ()
    {
//        let token = NSUserDefaults.standardUserDefaults().valueForKey("access_token") as? String

        let url = NSURL(string: "som url")

        let session = NSURLSession.sharedSession()

        let request = NSURLRequest(URL: url!)

        let dataTask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
            // print("done, error: \(error)")

            if error == nil
            {

                dispatch_async(dispatch_get_main_queue())
                {
                    self.arrDict=(try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! NSMutableArray
                    if (self.arrDict.count>0)
                    {
                        self.FavTableView.reloadData()
                    }
                }

            }


        }
        dataTask.resume()
}
 func numberOfSectionsInTableView(tableView: UITableView) -> Int
    {
//        return self.FData.count
        return self.arrDict.count
    }


    // number of rows
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return 1
    }

    // height for each cell
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat
    {
        return cellSpacingHeight
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {

        let cell:FavCell = self.FavTableView.dequeueReusableCellWithIdentifier("FCell") as! FavCell
        cell.FLabel1.text=arrDict[indexPath.section] .valueForKey("favourite_name") as? String
        cell.FLabel2.text=arrDict[indexPath.section] .valueForKey("favourite_address") as? String
        return cell

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

请帮帮我。

提前致谢

为了解决您的问题,正如@El Capitan所提到的,您需要使用didSelectRowAtIndexPath方法来更改其状态。 你的代码应该看起来像这样:

// Declare a variable which stores checked rows. UITableViewCell gets dequeued and restored as you scroll up and down, so it is best to store a reference of rows which has been checked
var rowsWhichAreChecked = [NSIndexPath]()

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
      let cell:FavCell = tableView.cellForRowAtIndexPath(indexPath) as! FavCell
      // cross checking for checked rows
      if(rowsWhichAreChecked.contains(indexPath) == false){
         cell.checkBox.isChecked = true
         rowsWhichAreChecked.append(indexPath) 
      }else{
         cell.checkBox.isChecked = false
         // remove the indexPath from rowsWhichAreCheckedArray
         if let checkedItemIndex = rowsWhichAreChecked.indexOf(indexPath){
            rowsWhichAreChecked.removeAtIndex(checkedItemIndex)
         }
      }
}

要重新显示在将视图滚动到视图之外之前已检查过的单元格,请在您的cellForRowAtIndexPathrowsWhichAreChecked数组执行相同的检查并相应地设置其状态。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

let cell:FavCell = self.FavTableView.dequeueReusableCellWithIdentifier("FCell") as! FavCell
cell.FLabel1.text=arrDict[indexPath.section] .valueForKey("favourite_name") as? String
cell.FLabel2.text=arrDict[indexPath.section] .valueForKey("favourite_address") as? String


   if(rowsWhichAreChecked.contains(indexPath) == false){
         cell.checkBox.isChecked = true
    }else{
        cell.checkBox.isChecked = false
    }
  }
    return cell           
}

编辑答案

我已经让你的代码工作,但我必须对你的Checkbox类和ViewController进行一些修改

Checkbox.swift

class CheckBoxButton: UIButton {

    // Images
    let checkedImage = UIImage(named: "CheckBoxChecked")! as UIImage
    let uncheckedImage = UIImage(named: "CheckBoxUnChecked")! as UIImage

    // Bool property
    var isChecked: Bool = false {
        didSet{
            if isChecked == true {
                self.setImage(uncheckedImage, forState: .Normal)
            } else {
                self.setImage(checkedImage, forState: .Normal)
            }
        }
    }

    override func awakeFromNib() {
        self.userInteractionEnabled = false
//        self.addTarget(self, action: #selector(CheckBoxButton.buttonClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside)
//        self.isChecked = false
    }

    func buttonClicked(sender: UIButton) {
        if sender == self {
            if isChecked == true {
                isChecked = false
            } else {
                isChecked = true
            }
        }
    }

}

ViewController.swift

class FavVC: UIViewController, UITableViewDelegate, UITableViewDataSource {


    @IBOutlet weak var FavTableView: UITableView!


    var rowsWhichAreChecked = [NSIndexPath]()

    //var FData = [FavouritesData]()

    var arrDict :NSMutableArray=[]

    let cellSpacingHeight: CGFloat = 5  // cell spacing from each cell in table view

    override func viewDidLoad() {

        self.FavTableView.delegate = self
        self.FavTableView.dataSource = self

        super.viewDidLoad()

        self.jsonParsingFromURL()

        let nib = UINib(nibName:"FavCell", bundle: nil)

        FavTableView.registerNib(nib, forCellReuseIdentifier: "FCell")

    }

    // web services method
    func jsonParsingFromURL ()
    {
//        let token = NSUserDefaults.standardUserDefaults().valueForKey("access_token") as? String

        let url = NSURL(string: "some url")

        let session = NSURLSession.sharedSession()

        let request = NSURLRequest(URL: url!)

        let dataTask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
            // print("done, error: \(error)")

            if error == nil
            {

                dispatch_async(dispatch_get_main_queue())
                {
                    self.arrDict=(try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)) as! NSMutableArray
                    if (self.arrDict.count>0)
                    {
                        self.FavTableView.reloadData()
                    }
                }

            }


        }
        dataTask.resume()

//        
//        let StringUrl = "http"+token!

//        let url:NSURL = NSURL(string: StringUrl)!

//        if let JSONData = NSData(contentsOfURL: url)
//        {
//            if let json = (try? NSJSONSerialization.JSONObjectWithData(JSONData, options: [])) as? NSDictionary
//            {
//                for values in json
//                {
//                    self.FData.append()
//                }

//                if let reposArray = json["data"] as? [NSDictionary]
//                {
//                    
//                    for item in reposArray
//                    {
//                        let itemObj = item as? Dictionary<String,AnyObject>
//                        
//                        let b_type = itemObj!["business_type"]?.valueForKey("type")
//                        
//                        //self.Resultcount.text = "\(b_type?.count) Results"
//                        
//                        if (b_type as? String == "Taxis")
//                        {
//                            
//                            self.FData.append(FavouritesData(json:item))
//                            
//                        }
//                    }
//                }

//            }
//        }

    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int
    {
//        return self.FData.count
        return self.arrDict.count
    }


    // number of rows
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return 1
    }

    // height for each cell
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat
    {
        return cellSpacingHeight
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {

        let cell:FavCell = self.FavTableView.dequeueReusableCellWithIdentifier("FCell") as! FavCell
        cell.FLabel1.text=arrDict[indexPath.section] .valueForKey("favourite_name") as? String
        cell.FLabel2.text=arrDict[indexPath.section] .valueForKey("favourite_address") as? String

        let isRowChecked = rowsWhichAreChecked.contains(indexPath)

        if(isRowChecked == true)
        {
            cell.checkbox.isChecked = true
            cell.checkbox.buttonClicked(cell.checkbox)
        }else{
            cell.checkbox.isChecked = false
            cell.checkbox.buttonClicked(cell.checkbox)
        }

    return cell
}

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let cell:FavCell = tableView.cellForRowAtIndexPath(indexPath) as! FavCell
        // cross checking for checked rows
        if(rowsWhichAreChecked.contains(indexPath) == false){
            cell.checkbox.isChecked = true
            cell.checkbox.buttonClicked(cell.checkbox)
            rowsWhichAreChecked.append(indexPath)
        }else{
            cell.checkbox.isChecked = false
            cell.checkbox.buttonClicked(cell.checkbox)
            // remove the indexPath from rowsWhichAreCheckedArray
            if let checkedItemIndex = rowsWhichAreChecked.indexOf(indexPath){
                rowsWhichAreChecked.removeAtIndex(checkedItemIndex)
            }
        }
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
 {
        let cell:FilterTableViewCell = tableView.dequeueReusableCell(withIdentifier: "filtercell", for: indexPath) as! FilterTableViewCell

        // Configure the cell...
        cell.lblCategory?.attributedText = FontAttributes.sharedInstance.AttributesString(message: self.filterArray[indexPath.row], color: Textcolor)

        cell.BtnIndex?.addTarget(self, action: #selector(checkMarkTapped(_ :)), for: .touchUpInside)
        cell.BtnIndex?.tag = indexPath.row


        let rowid = indexPath.row
        let found = rowsWhichAreChecked.filter{$0.rowId == rowid}.count > 0
        if found
        {
             cell.BtnIndex?.setImage(checkedImage, for: .normal)
        }
        else
        {
             cell.BtnIndex?.setImage(uncheckedImage, for: .normal)

        }
        return cell
    }

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


        let cell:FilterTableViewCell = tableView.cellForRow(at: indexPath) as! FilterTableViewCell



        let rowid = indexPath.row

       let found = rowsWhichAreChecked.filter{$0.rowId == rowid}.count > 0

        if found
        {
            tempArrayFordelete = rowsWhichAreChecked
            for obj in tempArrayFordelete
            {
                if let index = rowsWhichAreChecked.index(where: { $0.rowId == obj.rowId }) {
                    // removing item
                    rowsWhichAreChecked.remove(at: index)
                    cell.BtnIndex?.setImage(uncheckedImage, for: .normal)
                }
            }
        }
        else
        {

            cell.BtnIndex?.setImage(checkedImage, for: .normal)
            let objrowId = selectedIndex(rowId: indexPath.row)
            rowsWhichAreChecked.append(objrowId)
        }




    }

我很高兴通知你所有解决上述问题的人

解决问题是

  1. CheckBox功能
  2. RadioButton功能
  3. ReuseCell(tableView.dequeueReusableCell)//也解决了选定的单元格位置问题。

经过测试的代码

  • 斯威夫特5
  • iOS 12.2

这是我的代码

import UIKit

class countrySelection:UITableViewCell{
     @IBOutlet weak var imgFlag: UIImageView!
     @IBOutlet weak var lblCountryName: UILabel!
     @IBOutlet weak var btnSelection: UIButton!
}

class ViewController: UIViewController {

    var listingDict=[[String:String]]()

    var radioOption:Int?// Only used :: if u are 2. RadioButton Functionality implement

    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.dataSource=self
        tableView.delegate=self

        fillCountryData()
        // Do any additional setup after loading the view.
    }

    func fillCountryData(){
        self.fillJsonData(imgName: "india_flag", countryName: "India")
        self.fillJsonData(imgName: "pakistan_flag", countryName: "Pakistan")
        self.fillJsonData(imgName: "israel_flag", countryName: "Israel")
        self.fillJsonData(imgName: "albania_flag", countryName: "Albania")
        self.fillJsonData(imgName: "america_flag", countryName: "America")
        self.fillJsonData(imgName: "belize_flag", countryName: "Belize")
        self.fillJsonData(imgName: "brunei_flag", countryName: "Brunei")
        self.fillJsonData(imgName: "comoros_flag", countryName: "Comoros")
        self.fillJsonData(imgName: "congo_flag", countryName: "Congo")
        self.fillJsonData(imgName: "ecuador_flag", countryName: "Ecuador")
        self.fillJsonData(imgName: "haiti_flag", countryName: "Haiti")
        self.fillJsonData(imgName: "jamaica_flag", countryName: "Jamaica")
        self.fillJsonData(imgName: "kenya_flag", countryName: "Kenya")
        self.fillJsonData(imgName: "mali_flag", countryName: "Mali")

        self.tableView.reloadData()
    }

    func fillJsonData(imgName:String,countryName:String){
        var dictData=[String:String]()
        dictData["img"]=imgName
        dictData["country"]=countryName
        dictData["check"]="false"
        listingDict.append(dictData)
    }

}

extension ViewController:UITableViewDataSource,UITableViewDelegate{

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell=tableView.dequeueReusableCell(withIdentifier: "countrySelection") as! countrySelection
        let dictVal=listingDict[indexPath.row]
        cell.lblCountryName.text=dictVal["country"]
        cell.imgFlag.image=UIImage(named:dictVal["img"]!)

        /*//Check Box Functionality
        if dictVal["check"] == "false"{
            cell.btnSelection.setImage(UIImage(named: "checkbox_UnSelect"), for: .normal)
        } else{
            cell.btnSelection.setImage(UIImage(named: "checkbox_Select"), for: .normal)
        }*/

        //RadioButton Functionality
        if radioOption==indexPath.row{
            listingDict[indexPath.row]["check"]="true"
            cell.btnSelection.setImage(UIImage(named: "radioButton_Select"), for: .normal)
        } else{
            listingDict[indexPath.row]["check"]="false"
            cell.btnSelection.setImage(UIImage(named: "radioButton_UnSelect"), for: .normal)
        }

        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        /*//CheckBox Functionality
        if listingDict[indexPath.row]["check"]=="true"{
            listingDict[indexPath.row]["check"]="false"
        } else{
            listingDict[indexPath.row]["check"]="true"
        }*/
        //RadioButton Functionality
        print("RadioButton",listingDict)
        if listingDict[indexPath.row]["check"]=="true"{
            radioOption=nil
        } else{
            radioOption=indexPath.row
        }

        self.tableView.reloadData()
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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