2017-08-21 88 views
-1

在这我有三个部分,其中我需要最后一节tableviewcell数据需要传递到表视图类,但我想使用nsnotificationcenter传递数据我已经看到很多答案,但无法正确理解如何通过谁能帮助我如何使用nsnotification如何将数据从表视图单元格类传递到视图控制器表视图类?

表视图类

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 
     } 
+0

为什么通知?要求一对多吗?如果不是,我宁愿交出(代表),这是一对一的。 –

+0

如果可能的话,委托人也没有问题任何人@TusharSharma –

+0

我只需要一对一的方式,即从表视图单元格类到表视图类@TusharSharma –

回答

0

发布的数据,而不是在UITable创造IBAction为的ViewCell类,addTarget您在ViewControllercellForRow方法按钮: -

cell.radioButton.addTarget(self, action: #selector(YourViewController.someMethod(_sender:)), for: UIControlEvents.touchUpInside) 

,然后调用您的视图控制器本身的API,让你不会有来传递数据: -

func someMethod(_sender: UIButton) 
{ 
    // Call your Api here in View Controller Class 
} 
+0

我需要获取表视图单元格中的self.shippingHeightConstraint.constant值以在表视图类中使用如何使用?@Ashish Pisey –

+0

self.shippingHeightConstraint.constant = CGFloat(sectionHeight + cellHeight)我需要获取这个值并在表视图类中使用@Ashish Pisey –

+0

但我需要在表视图类中加载数据,请参阅我编辑过的问题我的代码 –

相关问题