通过点击表视图中的单元格以及如何知道哪个单元格已选中或未选中来选中取消选中复选框

通过点击表视图中的单元格以及如何知道哪个单元格已选中或未选中来选中取消选中复选框,第1张

通过点击表视图中的单元格以及如何知道哪个单元格已选中或未选中来选中/取消选中复选框

为了解决您的问题,如@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 checkedvar 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)         }      }}

要重新显示滚动到视线之外的行之前检查过的单元格,请在处

cellForRowAtIndexPath
rowsWhichAreChecked
array
执行相同的检查,并相应地设置其状态。

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {let cell:FavCell = self.FavTableView.dequeueReusableCellWithIdentifier("FCell") as! FavCellcell.FLabel1.text=arrDict[indexPath.section] .valueForKey("favourite_name") as? Stringcell.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.    }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5642209.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存