【问题标题】:How to use UITableView with cell having UISwitch and adding one switch for Select all?如何将 UITableView 与具有 UISwitch 的单元格一起使用并为全选添加一个开关?
【发布时间】:2016-08-26 16:55:44
【问题描述】:

这是第二个屏幕

第三屏

如果你可以在图像中注意到表格视图中的第一项是 全选,并且该单元格中有相应的 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.
     }
     */

}

我的 UITableview 单元格的代码是

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 开发新手

【问题讨论】:

    标签: ios swift uitableview swift2 uiswitch


    【解决方案1】:
    • Customer类/结构中添加属性selected
    • 根据selected更新cellForRowAtIndexPath中的开关状态
    • didChangeSwitchState 中,如果索引路径不为0,则更新相应Customer 对象的属性,如果索引路径为0,则在数据源数组中设置all selected 属性和重新加载表格视图。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:
        //
        //  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!
            }
            
            
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-10-20
          • 2011-04-15
          • 2021-01-16
          • 2018-04-12
          • 1970-01-01
          相关资源
          最近更新 更多