简体   繁体   English

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

[英]Swipe to delete works, but the delete button doesn't

I have a UITableView. 我有一个UITableView。 When the I tap the Edit button, it goes into editing mode, but the red '-' buttons on each cell don't make the Delete button appear. 当我点击编辑按钮时,它进入编辑模式,但每个单元格上的红色“ - ”按钮不会显示“删除”按钮。

Here's the code I used for this: 这是我用于此的代码:

//
//  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()
    }



}

Swiping the cell does make the delete button appear, and it deletes the cell and data properly, so I can't figure out what I'm doing wrong! 滑动单元格会使删除按钮出现,并且它会正确删除单元格和数据,所以我无法弄清楚我做错了什么!

Thanks. 谢谢。

Edit: Here is a link to the Xcode project. 编辑: 这是Xcode项目的链接。

Dont forget to put this in cellForRowAtIndexPath 别忘了把它放在cellForRowAtIndexPath中

 cell.editingAccessoryType = .DetailDisclosureButton

You also need to do 你还需要做

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

ok, the problem is the tapgesturerecognizer in your navigationcontroller. 好的,问题是你的navigationcontroller中的tapgesturerecognizer。 if you want to keep it you could use something like the following: 如果你想保留它,你可以使用以下内容:

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
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM