swift2 如何在单元格有UISwitch的情况下使用UITableView,并为Select all增加一个开关?

q1qsirdb  于 2022-11-06  发布在  Swift
关注(0)|答案(3)|浏览(166)

这是第二个屏幕

此第3次筛选

如果您注意到图中的tableview中的第一个项目是Select All,并且在该单元格中有一个相应的Uiswitch
我想让tableview中的其余所有uiSwitch在切换全选时切换。
我的视图控制器代码是

import UIKit
import Alamofire
import SwiftyJSON

protocol SettingCellDelegate : class {
    func didChangeSwitchState(sender: CustomerTableViewCell, isOn: Bool)
}

class CutomerListViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,SettingCellDelegate {

    @IBOutlet weak var CustomerTableView: UITableView!

    var refreshControl: UIRefreshControl!

    var mList = NSMutableOrderedSet()

    let cellSpacingHeight: CGFloat = 8

    var cId: [String] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        //print("selected customer")
        //print (cId)
        getListOfCustomer()
        // Do any additional setup after loading the view.
    }

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

    var mCustomerList : [Customer] = []

    func getListOfCustomer(){

        //print("Getting List Of Woises")
        let ud = NSUserDefaults.standardUserDefaults()

        let decoded  = ud.objectForKey("userObject") as! NSData
        let user = NSKeyedUnarchiver.unarchiveObjectWithData(decoded) as! UserObject

        let url = Request.getListCustomer()+user.CompanyID
        print(url)
        Alamofire.request(.GET, url)
            .validate()
            .responseJSON { (_ ,_ ,result) in
                switch result {
                case .Success(let data):
                    let jsonResponse = JSON(data)
                    //print("JSON")
                    print(jsonResponse)
                    var mCustomer: Customer

                    self.mCustomerList.append(Customer(CustomerID: "0", CustomerName: "Select All", Username: "", Password: "", IsActive: "", ContactPersonEmail: "", ContactPersonPhone: "", CompanyID: "", CustomerRevenue: "", ContactPerson: "", CustomerURL: "", Country: "", Logo: "", CustomerPriority: "", CustomerSatisfaction: "", CustomerStatus: "", CustomerCreatedOn: "", CustomerRegion: "", CreatedBy: "", UpdatedBy: "", ID: ""))
                    for i in 0  ..< jsonResponse["document"].count {

                        mCustomer = Customer(
                         CustomerID: jsonResponse["document"][i]["CustomerID"].description,
                         CustomerName: jsonResponse["document"][i]["CustomerName"].description,
                         Username: jsonResponse["document"][i]["Username"].description,
                         Password: jsonResponse["document"][i]["Password"].description,
                         IsActive: jsonResponse["document"][i]["IsActive"].description,
                         ContactPersonEmail: jsonResponse["document"][i]["ContactPersonEmail"].description,
                         ContactPersonPhone: jsonResponse["document"][i]["ContactPersonPhone"].description,
                         CompanyID: jsonResponse["document"][i]["CompanyID"].description,
                         CustomerRevenue: jsonResponse["document"][i]["CustomerRevenue"].description,
                         ContactPerson: jsonResponse["document"][i]["ContactPerson"].description,
                         CustomerURL: jsonResponse["document"][i]["CustomerURL"].description,
                         Country: jsonResponse["document"][i]["Country"].description,
                         Logo: jsonResponse["document"][i]["Logo"].description,
                         CustomerPriority: jsonResponse["document"][i]["CustomerPriority"].description,
                         CustomerSatisfaction: jsonResponse["document"][i]["CustomerSatisfaction"].description,
                         CustomerStatus: jsonResponse["document"][i]["CustomerStatus"].description,
                         CustomerCreatedOn: jsonResponse["document"][i]["CustomerCreatedOn"].description,
                         CustomerRegion: jsonResponse["document"][i]["CustomerRegion"].description,
                         CreatedBy: jsonResponse["document"][i]["CreatedBy"].description,
                         UpdatedBy: jsonResponse["document"][i]["UpdatedBy"].description,
                         ID: jsonResponse["document"][i]["ID"].description)

                        self.mCustomerList.append(mCustomer)
                        self.mList.addObjectsFromArray(self.mCustomerList)

                    }

                    print("CUSTOMER Count"+String(self.mList.count))
                    if(self.CustomerTableView != nil){
                        self.CustomerTableView.reloadData()
                    }

                    /*  print("mlist printed from fetchNotification API")
                     print(self.mList)
                     print("mList count from fetchNotification API")
                     print(self.mList.count)*/
                case .Failure(let error):
                    print("Request failed with error: \(error)")
                }
        }

    }

    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return self.cellSpacingHeight
    }

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

    internal func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
        CustomerTableView = tableView
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CustomerTableViewCell

        if mList.count > 0{
            let mCustomer = mList.objectAtIndex(indexPath.row) as! Customer

            cell.Title?.text = mCustomer.CustomerName

            if self.cId.contains(mCustomer.CustomerID) || self.cId.contains(" " + mCustomer.CustomerID){
                cell.SelectionStatus.setOn(true, animated:true)
            }else{
                cell.SelectionStatus.setOn(false, animated:true)
            }
            cell.cellDelegate = self

        }
        return cell

    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    }

    func didChangeSwitchState(sender: CustomerTableViewCell, isOn: Bool) {
        let indexPath = self.CustomerTableView.indexPathForCell(sender)

    }
    /*
     // MARK: - Navigation

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

}

我的UITTableview单元格的代码是

import UIKit

class CustomerTableViewCell: UITableViewCell {

    @IBOutlet weak var Title: UILabel!
    @IBOutlet weak var SelectionStatus: UISwitch!
    weak var cellDelegate: SettingCellDelegate?
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    @IBAction func handledSwitchChange(sender: UISwitch) {
        self.cellDelegate?.didChangeSwitchState(self, isOn:SelectionStatus.on)
        print("select all uday")
       }

}

请帮助我,我是iOS开发新手

eyh26e7m

eyh26e7m1#

  • Customer类/结构中添加属性selected
  • 根据selected更新cellForRowAtIndexPath中交换机的状态
  • didChangeSwitchState中,如果索引路径不为0,则更新相应Customer对象的该属性;如果索引路径为0,则设置数据源数组中的allselected属性,并重新加载表视图。
wswtfjt7

wswtfjt72#

is Select all总是在索引0中,那么u可以在didChangeSwitchState上创建一个条件,检查索引是否为0,然后添加/删除(基于开关值)self.cId中的所有cID,然后重新加载表

7fhtutme

7fhtutme3#

//
//  ViewController.swift
//  Switch_SelectAll
//
//  Created by Sivakumar on 13/10/20.
//

import UIKit

var allCharacters:[Character] = []

struct Character
{
    var name:String
    var isSelected:Bool = false
    init(name:String) {
        self.name = name
    }
}

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        allCharacters = [Character(name: "Select All"),Character(name: "Dhoni"),Character(name: "Virat"),Character(name:"Raina"),Character(name:"ABD")]
    }

    @objc func switchSelected(sender:UISwitch){
        if sender.tag == 0
        {
          allCharacters[sender.tag].isSelected = !allCharacters[sender.tag].isSelected
            print("indices",allCharacters.indices)
          for index in allCharacters.indices
          {
            allCharacters[index].isSelected = allCharacters[sender.tag].isSelected
          }
        }
        else
        {
          allCharacters[sender.tag].isSelected = !allCharacters[sender.tag].isSelected
          if allCharacters.dropFirst().filter({ $0.isSelected }).count == allCharacters.dropFirst().count
          {
            allCharacters[0].isSelected = true
          }
          else
          {
            allCharacters[0].isSelected = false
          }
        }
        tableView.reloadData()
    }

}

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? CustomTableViewCell

      cell?.textLabel?.text = allCharacters[indexPath.row].name
      if allCharacters[indexPath.row].isSelected
      {
        cell?.SelectionStatus.isOn = true
      }
      else
      {
        cell?.SelectionStatus.isOn = false
      }
        cell?.SelectionStatus.tag = indexPath.row
        cell?.SelectionStatus.addTarget(self, action: #selector(switchSelected(sender:)), for: .touchUpInside)
    return cell!
    }

}

相关问题