如何将数据从表格视图单元格传回表格视图类?

Posted

技术标签:

【中文标题】如何将数据从表格视图单元格传回表格视图类?【英文标题】:how to pass the data back from table view cell to table view class? 【发布时间】:2017-08-21 04:32:30 【问题描述】:

在这三个部分中,我需要最后一个部分 tableviewcell 数据需要传递给 table view 类,而第一部分中的另一个部分我有单选按钮,只要它被启用,那么只需要显示第三部分在表格视图上,如果不是应该隐藏

表格视图类

    let url = "http://www.json-generator.com/api/json/get/bMlqRPbjGW?indent=2"
    let urlString = "http://www.json-generator.com/api/json/get/bVWKKHtWbm?indent=2"
    var shippingArray :[[String: AnyObject]] = []
    var keys = [String]()
    let myActivityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
    var arrayss =  [String:AnyObject]()
    var checkIsRadioselect = [Int]()
    var checkIsButtonEnable = [Int]()
    var checkIsPaymentRadioSelect = [Int]()
    let response : [Int] = []
    var chekIndex:IndexPath?
    var selected: Bool = true
    var dataArray :[Any] = []
    var A: [Any] = []
    var B: [Any] = []

    override func viewDidLoad() 
        super.viewDidLoad()
        _ = UIApplication.shared.statusBarOrientation
        tableDetails.isHidden = true
        continueButton.layer.cornerRadius = 5
        myActivityIndicator.frame = CGRect(x: 130, y: 320, width: 30, height: 30)
        myActivityIndicator.hidesWhenStopped = true
        myActivityIndicator.startAnimating()
        view.addSubview(myActivityIndicator)
        myActivityIndicator.translatesAutoresizingMaskIntoConstraints = false
        let horizontalConstraint = NSLayoutConstraint(item: myActivityIndicator, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
        view.addConstraint(horizontalConstraint)
        let verticalConstraint = NSLayoutConstraint(item: myActivityIndicator, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)
        view.addConstraint(verticalConstraint)
        self.shippingaddressURL()
        tableDetails.delegate = self
        tableDetails.dataSource = self
        tableDetails.separatorInset = UIEdgeInsets.zero
        tableDetails.rowHeight = UITableViewAutomaticDimension
        tableDetails.estimatedRowHeight = 50
        self.title = "Checkout"
        // Do any additional setup after loading the view.
    
      func shippingaddressURL() 
        let url = NSURL(string: self.url)
        URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: (data, response, error) -> Void in
            if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary 
            self.shippingArray = (jsonObj!.value(forKey: "address") as? [[String: AnyObject]])!
                OperationQueue.main.addOperation(
                    self.tableDetails.reloadData()
                )
            
        ).resume()
    
    @IBAction func selectRadioButton(_ sender: KGRadioButton) 
        let chekIndex = self.checkIsRadioSelect.index(of: sender.tag)
        _ = self.checkIsButtonEnable.index(of: sender.tag)
        if sender.isSelected 

         else
            if(chekIndex == nil)
                self.checkIsRadioSelect.removeAll(keepingCapacity: false)
                self.checkIsRadioSelect.append(sender.tag)
                self.checkIsButtonEnable.removeAll(keepingCapacity: false)
                self.checkIsButtonEnable.append(sender.tag)
                self.tableDetails.reloadData()
            
        
    
    func numberOfSections(in tableView: UITableView) -> Int
        return 3
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? 
        if (section == 0)
            return "SHIPPING ADDRESS"
        
        else if (section == 2)
            return "SHIPPING METHOD"
        
        else
            return ""
        
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
        if (indexPath.section == 0)
            return UITableViewAutomaticDimension
        
        else if (indexPath.section == 1)
            return 62
        
        else 
            return 282
        
    

    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int)
        let header = view as! UITableViewHeaderFooterView
        header.textLabel?.textColor = UIColor.gray
        header.textLabel?.textAlignment = NSTextAlignment.center
        header.textLabel?.font = UIFont(name: "Futura", size: 17)
    

    @IBAction func newAddressAction(_ sender: Any) 
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let addtoCartVC = storyboard.instantiateViewController(withIdentifier: "newAddress") as! NewAddressViewController
        self.navigationController?.pushViewController(addtoCartVC, animated: true)
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
        if (section == 0)
            return shippingArray.count
        
        else 
            return 1
        
    
    @IBAction func continueButtonAction(_ sender: Any) 
        if selected == false
            let radiobutton = SCLAlertView()
            _ =  radiobutton.showError("Warning", subTitle: "Please select shipping method", closeButtonTitle: "OK")

        else
            let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let addtoCartVC = storyboard.instantiateViewController(withIdentifier: "payment") as! PaymentMethodViewController
            self.navigationController?.pushViewController(addtoCartVC, animated: true)
        
    
    @IBAction func deleteAction(_ sender: UIButton) 
        shippingArray.remove(at:sender.tag)
        self.tableDetails.reloadData()
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
        if (indexPath.section == 0)
        
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! AddressTableViewCell
            tableDetails.isHidden = false
            myActivityIndicator.stopAnimating()
            let arr = shippingArray[indexPath.row]
            cell.deleteButton.tag = indexPath.row
            cell.nameLabel.text = arr["name"] as? String
            cell.addressLabel.text = arr["address"]as? String
            let mobilenumber : Any =  arr["number"] as AnyObject
            cell.mobileNumberLabel.text = "\(mobilenumber)"
            cell.radioButton.tag = indexPath.row
            cell.editButton.tag = indexPath.row
            cell.deleteButton.tag = indexPath.row
            cell.editButton.isHidden = true
            cell.deleteButton.isHidden = true
            let checkIndex = self.checkIsRadioSelect.index(of: indexPath.row)
            if(checkIndex != nil)
                cell.radioButton.isSelected = true
                cell.editButton.isHidden = false
                cell.deleteButton.isHidden = false
            else
            
                cell.radioButton.isSelected = false
                cell.editButton.isHidden = true
                cell.deleteButton.isHidden = true
            
            return cell
        
        else if (indexPath.section == 1)
            let cell = tableView.dequeueReusableCell(withIdentifier: "addresscell", for: indexPath) as! CreateNewAddressTableViewCell
            cell.newAddressButton.addTarget(self, action: #selector(newAddressAction(_:)), for: .touchUpInside)
            return cell
        
        else 
            let cell = tableView.dequeueReusableCell(withIdentifier: "shippingmethodcell", for: indexPath) as! MethodTableViewCell
            return cell
        
    

表格视图单元格类

   var chekIndex:IndexPath?
    var arrayss =  [String:AnyObject]()
    var keys = [String]()
    let urlString = "http://www.json-generator.com/api/json/get/bVgbyVQGmq?indent=2"

    override func awakeFromNib() 
        super.awakeFromNib()
        self.shippingmethodURL()
        shippingTableView.delegate = self
        shippingTableView.dataSource = self
        shippingTableView.rowHeight = UITableViewAutomaticDimension
        shippingTableView.estimatedRowHeight = shippingTableView.rowHeight
        // Initialization code
    
    @IBAction func paymentRadioAction(_ sender: KGRadioButton) 
        _ = sender.center
        let centralPoint = sender.superview?.convert(sender.center, to:self.shippingTableView)
        let indexPath =  self.shippingTableView.indexPathForRow(at: centralPoint!)
        if sender.isSelected 

         else
            chekIndex = indexPath
            isSelected = true
            self.shippingTableView.reloadData()
        
    
    func shippingmethodURL() 
        let url = NSURL(string: self.urlString)
        URLSession.shared.dataTask(with: (url as URL?)!, completionHandler: (data, response, error) -> Void in
            if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary 
                self.arrayss = jsonObj as! [String : AnyObject]
                print(self.arrayss)
                self.keys = jsonObj?.allKeys as! [String]
                print(self.keys)
                OperationQueue.main.addOperation(
                    self.shippingTableView.reloadData()
                    let sectionHeight = self.arrayss.count * 31
                    let cellHeight = self.keys.count * 44
                    self.shippingHeightConstraint.constant = CGFloat(sectionHeight + cellHeight)
                )
            
        ).resume()
    

    func numberOfSections(in tableView: UITableView) -> Int
        return arrayss.count
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? 
        return self.keys[section]
    
    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int)
        let header = view as! UITableViewHeaderFooterView
        header.tintColor = UIColor.white
        header.textLabel?.textColor = UIColor.darkGray
        header.textLabel?.textAlignment = NSTextAlignment.left
        header.textLabel?.font = UIFont(name: "Futura", size: 17)
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
        let key = self.keys[section]
        let a :[Any]  = arrayss[key] as! [Any]
        return a.count
    

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
        let cell = tableView.dequeueReusableCell(withIdentifier: "shippingCell", for: indexPath) as! ShippingMethodTableViewCell
        let bgColorView = UIView()
        bgColorView.backgroundColor = UIColor.white
        cell.selectedBackgroundView = bgColorView
        let key = self.keys[indexPath.section]
        var a :[Any]  = arrayss[key] as! [Any]
        var dictionary = a[indexPath.row] as! [String:Any]
        let name = dictionary["name"]
        let price = dictionary ["price"]
        cell.methodLabel.text = name  as? String
        cell.priceLabel.text = price as? String
        cell.radioButton.addTarget(self, action: #selector(paymentRadioAction), for: .touchUpInside)
        if chekIndex == indexPath 
            cell.radioButton.isSelected = true
         else 
            cell.radioButton.isSelected = false
        
        return cell
    

这里的布局如下所示

【问题讨论】:

【参考方案1】:
var addressSelected : Bool = false

@IBAction func selectRadioButton(_ sender: KGRadioButton) 
    let chekIndex = self.checkIsRadioSelect.index(of: sender.tag)
    _ = self.checkIsButtonEnable.index(of: sender.tag)
    tableDetails.tableFooterView?.isHidden = false
    if sender.isSelected 

     else
        if(chekIndex == nil)
            self.checkIsRadioSelect.removeAll(keepingCapacity: false)
            self.checkIsRadioSelect.append(sender.tag)
            self.checkIsButtonEnable.removeAll(keepingCapacity: false)
            self.checkIsButtonEnable.append(sender.tag)
            self.tableDetails.reloadData()
            self.addressSelected = true
            tableDetails.reloadData()
        
    

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
        if (addressSelected == false)
            if (section == 0)
                return shippingArray.count
            
            else if (section == 1) 
                return 1
            
            else
                return 0
            
        else
            if (section == 0)
            
                return shippingArray.count
            
            else
            
                return 1
            
        
    

【讨论】:

还需要如何将数据从表格视图单元格传递到表格视图类?

以上是关于如何将数据从表格视图单元格传回表格视图类?的主要内容,如果未能解决你的问题,请参考以下文章

如何从弹出视图控制器获取数据到自定义表格视图单元格?

如何从动态创建的表格视图单元格的输入字段中将数据检索到数组

使用委托将数据传回上一个VC并更新自定义单元格

如何从自定义表格视图单元类中获取对表格视图控制器的引用

将数据从自定义表格视图单元格传递到 UIView 控制器

如何从表格视图中的单元格点击图像视图