滑动以删除作品,但删除按钮不起作用

时间:2016-04-12 20:41:09

标签: ios iphone swift uitableview

我有一个UITableView。当我点击编辑按钮时,它进入编辑模式,但红色' - '每个单元格上的按钮都不会显示“删除”按钮。

这是我用于此的代码:

//
//  ViewController.swift
//  Measured Blood Lost
//
//  Created by Josh Birnholz on 4/11/16.
//  Copyright © 2016 Josh Birnholz. All rights reserved.
//

import UIKit

class MainViewController: UITableViewController, weightCellDelegate {

    @IBOutlet weak var totalWeightBarButtonItem: UIBarButtonItem!
    private var totalWeightLabel = UILabel(frame: CGRectZero)

    @IBOutlet weak var totalWeightTextField: UITextField!

    var totalWeight: Int = 0

    let availableWeights: [Weight] = [Weight(name: "Lap", weightInGrams: 22),
                                      Weight(name: "Lap counting bag", weightInGrams: 25),
                                      Weight(name: "Sterile green towel", weightInGrams: 90),
                                      Weight(name: "Sterile blue towel", weightInGrams: 55),
                                      Weight(name: "Kick bucket red bag", weightInGrams: 50),
                                      Weight(name: "Medium red bag", weightInGrams: 70),
                                      Weight(name: "Large red bag", weightInGrams: 120),
                                      Weight(name: "Washcloth", weightInGrams: 30),
                                      Weight(name: "Towel", weightInGrams: 192),
                                      Weight(name: "Blue cloth underpad", weightInGrams: 340),
                                      Weight(name: "Regular patient gown", weightInGrams: 340),
                                      Weight(name: "XL patient gown", weightInGrams: 498),
                                      Weight(name: "Under buttocks drape", weightInGrams: 76),
                                      Weight(name: "Mini lap", weightInGrams: 6),
                                      Weight(name: "Vag packing", weightInGrams: 16),
                                      Weight(name: "Pink peri pad", weightInGrams: 26),
                                      Weight(name: "Large white (Capri +)", weightInGrams: 40)
    ]

    var weights = [Weight]()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        totalWeightLabel.backgroundColor = UIColor.clearColor()
        totalWeightLabel.textAlignment = .Center
        totalWeightBarButtonItem.customView = totalWeightLabel

        navigationItem.leftBarButtonItem = editButtonItem()

        updateTotalWeightLabel()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

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

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)
        -> UITableViewCell {
            let cell = tableView.dequeueReusableCellWithIdentifier("WeightCell", forIndexPath: indexPath) as! WeightCell

            let name = weights[indexPath.row].name
            let weightInGrams = weights[indexPath.row].weightInGrams
            let quantity = weights[indexPath.row].quantity

            if let nameLabel = cell.viewWithTag(100) as? UILabel {
                nameLabel.text = "\(name.pluralize(quantity))"
                nameLabel.textColor = quantity == 0 ? UIColor.lightGrayColor() : UIColor.blackColor()
            }
            if let weightLabel = cell.viewWithTag(101) as? UILabel {
                weightLabel.text = "-\(weightInGrams * quantity) gm"
            }

            if let quantityTextField = cell.viewWithTag(102) as? UITextField {
                quantityTextField.text = quantity == 0 ? "" : String(quantity)
                cell.delegate = self
            }

            return cell
    }

    func quantityChanged(cell: WeightCell, newQuantity: Int, actionSender: AnyObject) {

        let point = actionSender.convertPoint(CGPointZero, toView: tableView)
        let indexPath = self.tableView.indexPathForRowAtPoint(point)!

        weights[indexPath.row].quantity = newQuantity
        tableView.reloadData()
        updateTotalWeightLabel()

    }

    @IBOutlet weak var addButton: UIBarButtonItem!

    @IBAction func addButtonPressed(sender: AnyObject) {

        addItems([randomWeight(), randomWeight()])

        updateTotalWeightLabel()

    }

    let nameTextField = UITextField()
    let weightTextField = UITextField()

    func randomWeight() -> Weight {

        let randomWeight = availableWeights[Int(arc4random_uniform(UInt32(availableWeights.count)))]
        let quantity = Int(arc4random_uniform(5))

        return Weight(name: randomWeight.name, weightInGrams: randomWeight.weightInGrams, quantity: quantity)
    }

    func addItems(weightsToAdd: [Weight]) {

        for weightToAdd in weightsToAdd {

            print("weightToAdd: \(weightToAdd.quantity) \(weightToAdd.name.pluralize(weightToAdd.quantity))")

            if weightToAdd.quantity > 0 {

                var foundIndex: Int?
                var index = 0
                for presentWeight in weights {
                    if presentWeight.name == weightToAdd.name {
                        foundIndex = index
                    }
                    index += 1
                }

                if foundIndex == nil {

                    weights.append(weightToAdd)
                    let indexPath = NSIndexPath(forRow: weights.count-1, inSection: 0)
                    tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)

                } else {
                    weights[foundIndex!].quantity += weightToAdd.quantity
                    tableView.reloadData()
                }


            }
        }
    }

    @IBAction func totalWeightTextFieldEditingBegan(sender: AnyObject) {

        if totalWeightTextField.text!.hasSuffix(" gm") {
            totalWeightTextField.text = totalWeightTextField.text!.substringToIndex(totalWeightTextField.text!.endIndex.advancedBy(-3))
        }

    }

    @IBAction func totalWeightTextFieldEditingEnded(sender: AnyObject) {

        totalWeightTextField.text!.numericize()

        if totalWeightTextField.text! == "" {
            totalWeight = 0
        } else {

            if let totalWeightInt = Int(totalWeightTextField.text!) {
                totalWeight = totalWeightInt
            } else {
                totalWeight = Int.max
            }

            totalWeightTextField.text = "\(String(totalWeight)) gm"

        }
        updateTotalWeightLabel()
    }

    func updateTotalWeightLabel() {

        var measuredBloodLost = totalWeight

        for weight in weights {
            measuredBloodLost = measuredBloodLost - (weight.weightInGrams * weight.quantity)
        }

        if measuredBloodLost < 0 {
            totalWeightLabel.textColor = UIColor.redColor()
        } else {
            totalWeightLabel.textColor = UIColor.blackColor()
        }

        totalWeightLabel.text = "Measured Blood Lost: \(measuredBloodLost) mL"
        totalWeightLabel.sizeToFit()
    }

    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return true
    }

    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Remove data
            weights.removeAtIndex(indexPath.row)
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
        }

        updateTotalWeightLabel()
    }



}

滑动单元格会显示删除按钮,并正确删除单元格和数据,这样我就无法弄清楚我做错了什么!

感谢。

修改:Here is a link to the Xcode project.

2 个答案:

答案 0 :(得分:1)

别忘了把它放在cellForRowAtIndexPath

 cell.editingAccessoryType = .DetailDisclosureButton

你还需要做

self.tableView.setEditing(true, animated: true)

答案 1 :(得分:1)

好的,问题是你的navigationcontroller中的tapgesturerecognizer。如果你想保留它,你可以使用以下内容:

class NavigationController : UINavigationController, UIGestureRecognizerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(NavigationController.dismissKeyboard))
        tap.delegate = self
        view.addGestureRecognizer(tap)
    }

    func dismissKeyboard() {
        view.endEditing(true)
    }

    func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
        if let view = touch.view where String(view.dynamicType) == "UITableViewCellEditControl" {
            print("do not receive touch")
            return false
        }

        print("do receive touch")
        return true
    }

}