提问者:小点点

如何计算从xcode tableView中选择的值


我想做一些像购物的东西,每当用户从UITableView中选择一个单元格时,该项目的价格将显示在total标签中,当他选择另一个项目时,两个项目的总和将显示在total标签中。 我做了一个plist,把东西存放在那里。 我现在要做的是如何将价格值分配到项目中,当用户选择单元格“项目”时,价格将显示出来。 这就是我目前所做的。 请帮帮我。

这是视图控制器:

(https://imgur.com/sqnz1yy)

import UIKit

class ServiceListViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {



    @IBOutlet weak var tablelbl: UITableView!





    var SerArr :[ServiceOB] = []
    var ArrService: [String] = []


    override func viewDidLoad() {
        super.viewDidLoad()

        tablelbl.delegate = self
        tablelbl.dataSource = self
        // Do any additional setup after loading the view.

        let path = Bundle.main.path(forResource: "ServiceList", ofType: "plist")

        let serArray : NSArray = NSArray(contentsOfFile: path!)!
        for service in serArray {
            print(service)
            let serviceOBJ = ServiceOB()

            // i change your plist to array


            serviceOBJ.Service = service as! String
            // check now..
            SerArr.append(serviceOBJ)
        }
    }






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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tablelbl.dequeueReusableCell(withIdentifier: "ServiceListCell") as! ServiceTableViewCell
        let obj = SerArr[indexPath.row]
        cell.servicelbl.text! = obj.Service

        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if tableView.cellForRow(at: indexPath)?.accessoryType == UITableViewCell.AccessoryType.checkmark{

            tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCell.AccessoryType.none        }
        else {
            tableView.cellForRow(at: indexPath)?.accessoryType = UITableViewCell.AccessoryType.checkmark

        }
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100.0
    }





}

共1个答案

匿名用户

创建一个tablecell的委托,并从tablecell中的按钮单击调用委托方法。

protocol tableCellDelegate {
   func callMethod()
}

class tableCell: UITableViewCell{
var delegate: tableCellDelegate?

@IBAction func selecteItem(_ sender: Any) {
  delegate?.callMethod()
}

class VC: UIViewController{
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> 
UITableViewCell {
  let cell = .....
  cell.delegate = self
  return cell
}

func callMethod(){
  // Do some thing}

}