mardi 2 février 2021

Expandable drop down with Multi select checkbox in Swift

check / uncheck the check box by tapping the cell in table view and how to know which cell has checked or unchecked inside Expandable drop down in Swift.

VBExpandVC

class VBExpandVC: UIViewController,UITableViewDelegate,UITableViewDataSource {

    @IBOutlet var myTableView: UITableView!
    
    struct Notification:Codable {
        let notification:[Headings]
    }
    
    struct Headings:Codable {
        var name:String
        var status:Int
    }
       
    var names = [Headings]()

    var expandTableview:VBHeader = VBHeader()
    var cell : VCExpandCell!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        getNotifications()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
    {
        expandTableview = Bundle.main.loadNibNamed("VBHeader", owner: self, options: nil)?[0] as! VBHeader
        let layer = expandTableview.viewHeader.layer
        layer.shadowColor = UIColor.black.cgColor
        layer.shadowOffset = CGSize(width: 0, height: 1)
        layer.shadowOpacity = 0.4
        expandTableview.lblDate.text = self.names[section].name
        expandTableview.btnExpand.tag = section
        expandTableview.btnExpand.addTarget(self, action: #selector(VBExpandVC.headerCellButtonTapped(_sender:)), for: UIControl.Event.touchUpInside)

        let str:String = "\(self.names[section].status)"//arrStatus[section] as! String
        if str == "0"
        {
            UIView.animate(withDuration: 2) { () -> Void in
                self.expandTableview.imgArrow.image = UIImage(named :"switch")
            }
        }
        else
        {
            UIView.animate(withDuration: 2) { () -> Void in
                self.expandTableview.imgArrow.image = UIImage(named :"switch2")
            }
        }

        return expandTableview
    }

    @objc func headerCellButtonTapped(_sender: UIButton)
    {
        print("header tapped at:")
        print(_sender.tag)
        var str:String = "\(self.names[_sender.tag].status)"
        if str == "0"
        {
            self.names[_sender.tag].status = 1
        }
        else
        {
            self.names[_sender.tag].status = 0
        }
//        myTableView.reloadData()
        myTableView.reloadSections([_sender.tag], with: .none)
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat
    {
        //Return header height as per your header hieght of xib
        return 40
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        let str:Int = (names[section].status)
        if str == 0
        {
            return 0
        }
        return  1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? VCExpandCell
        return cell;
    }

    func numberOfSections(in tableView: UITableView) -> Int
    {
        return self.names.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
    {
        //Return row height as per your cell in tableview
        return 111
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("selected:\(indexPath.section)")
    }
    
    // getNotifications
    func getNotifications(){
        guard let url = URL(string: "https://www.json-generator.com/api/json/get/cgAhRPmZgy?indent=2") else {
            return
        }
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        
        URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in
            guard let data = data, error == nil, response != nil else {
                return
            }
            
            do {
                let headings = try JSONDecoder().decode(Notification.self, from: data)
                self.names = headings.notification
                DispatchQueue.main.async {
                    self.myTableView.reloadData()
                }
            } catch {
                print(error)
            }
        }).resume()
    }
    // End
}

VCExpandCell

class VCExpandCell: UITableViewCell {
    
    @IBOutlet weak var btnMobile: UIButton!
    @IBOutlet weak var btnEmail: UIButton!
    @IBOutlet weak var btnSms: UIButton!
    
    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 btnMobileApp(_ sender: UIButton) {
        print("mobile app checked")
        print(sender.tag)
        if sender.isSelected {
            sender.isSelected = false
        } else {
            sender.isSelected = true
        }
    }
    
    @IBAction func btnSMS(_ sender: UIButton) {
        print("sms checked")
        print(sender.tag)

        if sender.isSelected {
          sender.isSelected = false
      } else {
          sender.isSelected = true
      }

    }

    @IBAction func btnEmail(_ sender: UIButton) {
        print("email checked")
        print(sender.tag)
        if sender.isSelected {
            sender.isSelected = false
        } else {
            sender.isSelected = true
        }
    }
    
}

enter image description here

In the above code, I have two major problems.

  1. selected check box positions are changing when expanded the section and expanded another section

  2. Unable to find selected check boxes by tapping the cell in table view inside Expand drop down.




Aucun commentaire:

Enregistrer un commentaire