我想做一些像购物一样的东西,每当用户从UITableView中选择一个单元格时,该项目价格将显示在总标签中,当他选择另一个项目时,两个项目的总和将显示在总标签中。
这是视图控制器。
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
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
}
}
创建一个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}
}
这很简单。只需获取使用的原始单元格类型的表单元格,并保留一个变量来存储总价的值。
@IBOutlet weak var priceLabel: UILabel!
var price: Double = 0.0 {
didSet {
// You can use localisation to change the currency. But that is currently not a part of the problem statement.
priceLabel?.text = "$\(price)"
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? ServiceTableViewCell {
// Assuming cell has a property for storing price: itemPrice
if cell.accessoryType == .checkmark {
totalPrice -= cell.itemPrice
cell.accessoryType = .none
} else {
totalPrice += cell.itemPrice
cell.accessoryType = .checkmark
}
}
}
注意:你不需要plist文件来存储选择的值。但如果你因为一些其他原因需要它,这里没有提到,你也可以根据选择改变plist的内容。