从按钮内删除表格中的一个单元格

huangapple go评论80阅读模式
英文:

remove a cell from my table from a button within

问题

以下是你提供的代码的翻译部分:

我在尝试从表格中删除单元格时遇到了问题,我尝试创建一些协议,但由于我对这种语言不熟悉,所以想不出很多解决方案。

扩展 CustomTableViewControllerUITableViewDataSource {

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

    func tableView(_ tableView: UITableView,
                   cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.row == sneakers.count {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: "OrderSummaryView") as? OrderSummaryView else {
                print("我永远不会打印")
                return OrderSummaryView()
            }

            return cell
        }

        let product = sneakers[indexPath.row]

        guard let cell = tableView.dequeueReusableCell(withIdentifier: "ExampleCell") as? ExampleCell else {
            print("我永远不会打印")
            return ExampleCell()
        }

        print("利用单元格")
        cell.configure(product: product)
        return cell
    }
}

这是我如何使用我的表格单元格

import UIKit

final class ExampleCell: UITableViewCell {

    private let productImageView: UIImageView = .init(frame: .zero)
    private let categoryLabel: UILabel = .init(frame: .zero)
    private let nameLabel: UILabel = .init(frame: .zero)
    private let priceLabel: UILabel = .init(frame: .zero)
    private let sizeLabel: UILabel = .init(frame: .zero)
    private let colorLabel: UILabel = .init(frame: .zero)

    private let removeButton = UIButton()
    // 用你的透明图片的名称替换 "transparent"
    private let clearImage = UIImage(named: "Image-1")
    let qtyButton = UIButton()
    private let arrowQty = UIImage(named: "Arrow_Qty")
    private let wishButton = UIButton()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: .default, reuseIdentifier: "ExampleCell")

        print("已创建新单元格")
        setupUI()
        setupConstraints()

    }

    // 使用 coder 进行初始化是当单元格通过 storyboard/XIB 实例化时
    required init?(coder: NSCoder) {
        fatalError("init(coder:) 尚未实现")
    }

    func configure(product: Product) {
        productImageView.image = product.image
        categoryLabel.text = product.category
        nameLabel.text = product.name
        priceLabel.text = "\(product.price)€"
        sizeLabel.text = "尺码:\(product.size)"
        colorLabel.text = "颜色:\(product.color)"
    }

    private func setupUI() {
        selectionStyle = .none

        let array = [productImageView,
                     categoryLabel,
                     nameLabel,
                     priceLabel,
                     sizeLabel,
                     colorLabel,
                     removeButton,
                     qtyButton,
                     wishButton]

        array.forEach { view in
            view.translatesAutoresizingMaskIntoConstraints = false
            addSubview(view)
        }

        contentView.translatesAutoresizingMaskIntoConstraints = false

        productImageView.layer.cornerRadius = 16

        categoryLabel.font = FontStyle.uiS.baseUIFont
        categoryLabel.textColor = UIColor(named: "GreyScale_400")

        nameLabel.font = FontStyle.displayMBold.baseUIFont
        nameLabel.textColor = UIColor(named: "GreyScale_700")

        priceLabel.font = FontStyle.uiS.baseUIFont
        priceLabel.textColor = UIColor(named: "GreyScale_700")

        sizeLabel.font = FontStyle.uiXS.baseUIFont
        sizeLabel.textColor = UIColor(named: "GreyScale_700")

        colorLabel.font = FontStyle.uiXS.baseUIFont
        colorLabel.textColor = UIColor(named: "GreyScale_700")

        removeButton.setImage(clearImage, for: .normal)

        qtyButton.setTitle("数量:1   ", for: .normal)
        qtyButton.setImage(arrowQty, for: .normal)
        qtyButton.semanticContentAttribute = .forceRightToLeft
        qtyButton.layer.cornerRadius = 16
        qtyButton.backgroundColor = UIColor(named: "GreyScale_White")
        qtyButton.setTitleColor(UIColor(named: "GreyScale_700"), for: .normal)
        qtyButton.layer.borderWidth = 1
        qtyButton.layer.borderColor = UIColor(named: "GreyScale_400")?.cgColor
        qtyButton.titleLabel?.font = FontStyle.uiM.baseUIFont

        wishButton.setTitle("移到愿望清单", for: .normal)
        wishButton.setTitleColor(UIColor(named: "GreyScale_700"), for: .normal)
        wishButton.titleLabel?.font = FontStyle.uiM.baseUIFont
        // 给愿望按钮添加下划线
        let attributedTitle = NSAttributedString(string: "移到愿望清单", attributes: [.underlineStyle: NSUnderlineStyle.single.rawValue])
        wishButton.setAttributedTitle(attributedTitle, for: .normal)
    }

    private func setupConstraints() {
        NSLayoutConstraint.activate([

            contentView.widthAnchor.constraint(equalToConstant: 350),
            contentView.heightAnchor.constraint(equalToConstant: 242),

            productImageView.topAnchor.constraint(equalTo: contentView.topAnchor),
            productImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 20),
            productImageView.widthAnchor.constraint(equalToConstant: 106),
            productImageView.heightAnchor.constraint(equalToConstant: 114),

            categoryLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 18),
            categoryLabel.leadingAnchor.constraint(equalTo: productImageView.trailingAnchor, constant: 32),
            categoryLabel.widthAnchor.constraint(equalToConstant: 29),
            categoryLabel.heightAnchor.constraint(equalToConstant: 14),

            nameLabel.topAnchor.constraint(equalTo: categoryLabel.bottomAnchor, constant: 8),
            nameLabel.leadingAnchor.constraint(equalTo: productImageView.trailingAnchor, constant: 32),
            nameLabel.widthAnchor.constraint(equalToConstant: 159),
            nameLabel.heightAnchor.constraint(equalToConstant: 24),

            priceLabel.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 8),
            priceLabel.leadingAnchor.constraint(equalTo: productImageView.trailingAnchor, constant: 32),
            priceLabel.widthAnchor.constraint(equalToConstant: 56),
            priceLabel.heightAnchor.constraint(equalToConstant: 14),

            sizeLabel.topAnchor.constraint(equalTo: priceLabel.bottomAnchor, constant: 16),
            sizeLabel.leadingAnchor.constraint(equalTo: productImageView.trailingAnchor, constant: 32),
            sizeLabel.widthAnchor.constraint(equalToConstant: 46),
            sizeLabel.heightAnchor.constraint(equalToConstant: 12),

            colorLabel.topAnchor.constraint(equalTo: priceLabel.bottomAnchor, constant: 16),
            colorLabel.leadingAnchor.constraint(equalTo: sizeLabel.trailingAnchor, constant: 16),
            colorLabel.widthAnchor.constraint(equalToConstant: 62),
            colorLabel.heightAnchor.constraint(equalToConstant: 12),

            removeButton.leadingAnchor.constraint(equalTo: contentView.trailingAnchor),
            removeButton.widthAnchor.constraint(equalToConstant: 12),
            removeButton.heightAnchor.constraint(equalToConstant: 12),

            qtyButton.topAnchor.constraint(equalTo: productImageView.bottomAnchor, constant: 32),
            qtyButton.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 32),
            qtyButton.widthAnchor.constraint(equalToConstant: 106),
            qtyButton.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 20),
            qtyButton.heightAnchor.constraint(equalToConstant: 64),

           

<details>
<summary>英文:</summary>

Im having trouble removing the cell from the table i tried to create some protocols but it didnt work since im new to this language i can&#39;t think of many solutions to this.

        extension CustomTableViewController: UITableViewDataSource {
        
        func tableView(_ tableView: UITableView,
                        numberOfRowsInSection section: Int) -&gt; Int {
             return sneakers.count + 1
         }
    
         func tableView(_ tableView: UITableView,
                        cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {
             
             
             if indexPath.row == sneakers.count {
                 guard let cell = tableView.dequeueReusableCell(withIdentifier: &quot;OrderSummaryView&quot;) as? OrderSummaryView else {
                     print(&quot;I&#39;ll never print&quot;)
                     return OrderSummaryView()
                 }
    
                 return cell
             }
    
             let product = sneakers[indexPath.row]
    
             guard let cell = tableView.dequeueReusableCell(withIdentifier: &quot;ExampleCell&quot;) as? ExampleCell else {
                 print(&quot;I&#39;ll never print&quot;)
                 return ExampleCell()
             }
    
             print(&quot;Utilize cells&quot;)
             cell.configure(product: product)
             return cell
         }
    
      
    }

this is how im using my table cells


   

    import UIKit
    
    
    
       final class ExampleCell: UITableViewCell {
        
        private let productImageView: UIImageView = .init(frame: .zero)
        private let categoryLabel: UILabel = .init(frame: .zero)
        private let nameLabel: UILabel = .init(frame: .zero)
        private let priceLabel: UILabel = .init(frame: .zero)
        private let sizeLabel: UILabel = .init(frame: .zero)
        private let colorLabel: UILabel = .init(frame: .zero)
        
        private let removeButton = UIButton()
        // Replace &quot;transparent&quot; with the name of your transparent image
        private let clearImage = UIImage(named: &quot;Image-1&quot;)
       let qtyButton = UIButton()
        private let arrowQty = UIImage(named: &quot;Arrow_Qty&quot;)
        private let wishButton = UIButton()
    
        
        override init(style: UITableViewCell.CellStyle,reuseIdentifier: String?) {
            super.init(style: .default,reuseIdentifier: &quot;ExampleCell&quot;)
            
            print(&quot;New cell has been create&quot;)
            setupUI()
            setupConstraints()
    
        }
        
        // Init with coder is when the cell is instaciated via storyboard/XIB
        required init?(coder: NSCoder) {
            fatalError(&quot;init(coder:) has not been implemented&quot;)
        }
        
        func configure(product: Product) {
            productImageView.image = product.image
            categoryLabel.text = product.category
            nameLabel.text = product.name
            priceLabel.text = &quot;\(product.price)&quot;
            sizeLabel.text = &quot;Size: \(product.size)&quot;
            colorLabel.text = &quot;Color: \(product.color)&quot;
        }
    
        
        private func setupUI() {
            selectionStyle = .none
            
            let array = [productImageView,
                         categoryLabel,
                         nameLabel,
                         priceLabel,
                         sizeLabel,
                         colorLabel,
                         removeButton,
                         qtyButton,
                         wishButton]
            
            array.forEach { view in
                view.translatesAutoresizingMaskIntoConstraints = false
                addSubview(view)
            }
            
            contentView.translatesAutoresizingMaskIntoConstraints = false
            
            productImageView.layer.cornerRadius = 16
            
            categoryLabel.font = FontStyle.uiS.baseUIFont
            categoryLabel.textColor = UIColor(named: &quot;GreyScale_400&quot;)
            
            nameLabel.font = FontStyle.displayMBold.baseUIFont
            nameLabel.textColor = UIColor(named: &quot;GreyScale_700&quot;)
            
            priceLabel.font = FontStyle.uiS.baseUIFont
            priceLabel.textColor = UIColor(named: &quot;GreyScale_700&quot;)
            
            sizeLabel.font = FontStyle.uiXS.baseUIFont
            sizeLabel.textColor = UIColor(named: &quot;GreyScale_700&quot;)
            
            colorLabel.font = FontStyle.uiXS.baseUIFont
            colorLabel.textColor = UIColor(named: &quot;GreyScale_700&quot;)
            
            removeButton.setImage(clearImage, for: .normal)
            
            qtyButton.setTitle(&quot;Qty:1   &quot;, for: .normal)
            qtyButton.setImage(arrowQty, for: .normal)
            qtyButton.semanticContentAttribute = .forceRightToLeft
            qtyButton.layer.cornerRadius = 16
            qtyButton.backgroundColor = UIColor(named: &quot;GreyScale_White&quot;)
            qtyButton.setTitleColor(UIColor(named: &quot;GreyScale_700&quot;), for: .normal)
            qtyButton.layer.borderWidth = 1
            qtyButton.layer.borderColor = UIColor(named: &quot;GreyScale_400&quot;)?.cgColor
            qtyButton.titleLabel?.font = FontStyle.uiM.baseUIFont
            
            wishButton.setTitle(&quot;Move to wishlist&quot;, for: .normal)
            wishButton.setTitleColor(UIColor(named: &quot;GreyScale_700&quot;), for: .normal)
            wishButton.titleLabel?.font = FontStyle.uiM.baseUIFont
            //underline wishButton
            let attributedTitle = NSAttributedString(string: &quot;Move to wishlist&quot;, attributes: [.underlineStyle: NSUnderlineStyle.single.rawValue])
            wishButton.setAttributedTitle(attributedTitle, for: .normal)
        }
        
        private func setupConstraints() {
            NSLayoutConstraint.activate([
                
                contentView.widthAnchor.constraint(equalToConstant: 350),
                contentView.heightAnchor.constraint(equalToConstant: 242),
                
                productImageView.topAnchor.constraint(equalTo: contentView.topAnchor),
                productImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 20),
                productImageView.widthAnchor.constraint(equalToConstant: 106),
                productImageView.heightAnchor.constraint(equalToConstant: 114),
                
                categoryLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 18),
                categoryLabel.leadingAnchor.constraint(equalTo: productImageView.trailingAnchor, constant: 32),
                categoryLabel.widthAnchor.constraint(equalToConstant: 29),
                categoryLabel.heightAnchor.constraint(equalToConstant: 14),
                
                nameLabel.topAnchor.constraint(equalTo: categoryLabel.bottomAnchor, constant: 8),
                nameLabel.leadingAnchor.constraint(equalTo: productImageView.trailingAnchor, constant: 32),
                nameLabel.widthAnchor.constraint(equalToConstant: 159),
                nameLabel.heightAnchor.constraint(equalToConstant: 24),
                
                priceLabel.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 8),
                priceLabel.leadingAnchor.constraint(equalTo: productImageView.trailingAnchor, constant: 32),
                priceLabel.widthAnchor.constraint(equalToConstant: 56),
                priceLabel.heightAnchor.constraint(equalToConstant: 14),
                
                sizeLabel.topAnchor.constraint(equalTo: priceLabel.bottomAnchor, constant: 16),
                sizeLabel.leadingAnchor.constraint(equalTo: productImageView.trailingAnchor, constant: 32),
                sizeLabel.widthAnchor.constraint(equalToConstant: 46),
                sizeLabel.heightAnchor.constraint(equalToConstant: 12),
                
                colorLabel.topAnchor.constraint(equalTo: priceLabel.bottomAnchor, constant: 16),
                colorLabel.leadingAnchor.constraint(equalTo: sizeLabel.trailingAnchor, constant: 16),
                colorLabel.widthAnchor.constraint(equalToConstant: 62),
                colorLabel.heightAnchor.constraint(equalToConstant: 12),
                
                removeButton.leadingAnchor.constraint(equalTo: contentView.trailingAnchor),
                removeButton.widthAnchor.constraint(equalToConstant: 12),
                removeButton.heightAnchor.constraint(equalToConstant: 12),
                
                qtyButton.topAnchor.constraint(equalTo: productImageView.bottomAnchor, constant: 32),
                qtyButton.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 32),
                qtyButton.widthAnchor.constraint(equalToConstant: 106),
                qtyButton.leadingAnchor.constraint(equalTo: contentView.leadingAnchor,constant: 20),
                qtyButton.heightAnchor.constraint(equalToConstant: 64),
               
                wishButton.topAnchor.constraint(equalTo: colorLabel.bottomAnchor, constant: 56),
                wishButton.leadingAnchor.constraint(equalTo: qtyButton.trailingAnchor, constant: 128),
                wishButton.widthAnchor.constraint(equalToConstant: 116),
                wishButton.heightAnchor.constraint(equalToConstant: 16),
            ])
        }
    }

this is where i declared the stuff thats inside the cells with this i want the remove button to remove the cell from the table and the view can u guys help me?



</details>


# 答案1
**得分**: 0

在你的单元格中添加一个按钮操作,然后添加一个闭包,以便你的单元格可以告诉表视图控制器按钮被点击了。

所以,在 `ExampleCell` ...

添加一个闭包:

```swift
final class ExampleCell: UITableViewCell {
    
    // 闭包
    var removeMe: ((ExampleCell) -> ())?

还在 ExampleCell 中,在你"设置UI"之后,为你的按钮添加一个动作:

removeButton.addTarget(self, action: #selector(removeButtonTapped(_:)), for: .touchUpInside)

选择器函数可以像这样:

@objc func removeButtonTapped(_ sender: UIButton) {
    print("Tapped remove button")

    // 调用闭包
    removeMe?(self)
}

现在,在你的控制器中,当你在 cellForRowAt 中取出单元格时,设置闭包:

let product = sneakers[indexPath.row]

guard let cell = tableView.dequeueReusableCell(withIdentifier: "ExampleCell") as? ExampleCell else {
    print("I'll never print")
    return ExampleCell()
}

print("Utilize cells")
cell.configure(product: product)

// 配置闭包
cell.removeMe = { [weak self] aCell in
    guard let self = self,
          let idxPath = self.tableView.indexPath(for: aCell)
    else { return }
    
    print("Update data and remove cell from table view...")
    self.sneakers.remove(at: idxPath.row)
    self.tableView.deleteRows(at: [idxPath], with: .automatic)
}

return cell

作为一个附注 - 当出队单元格时不要使用 guard let ...

// 不要这样做
//guard let cell = tableView.dequeueReusableCell(withIdentifier: "ExampleCell") as? ExampleCell else {
//    print("I'll never print")
//    return ExampleCell()
//}

// 像这样出队单元格
let cell = tableView.dequeueReusableCell(withIdentifier: "ExampleCell", for: indexPath) as! ExampleCell

如果你错误地注册了表视图单元格,你希望应用程序崩溃,以便你可以解决问题。

英文:

You want to add a button action in your cell, then add a closure so your cell can tell the table view controller that the button was tapped.

So, in ExampleCell ...

Add a closure:

final class ExampleCell: UITableViewCell {
// closure
var removeMe: ((ExampleCell) -&gt; ())?

also in ExampleCell - after you've "setup the UI", add an action for your button:

	removeButton.addTarget(self, action: #selector(removeButtonTapped(_:)), for: .touchUpInside)

the selector func can look like this:

@objc func removeButtonTapped(_ sender: UIButton) {
print(&quot;Tapped remove button&quot;)
// call the closure
removeMe?(self)
}

Now, in your controller, when you dequeue the cell in cellForRowAt, set the closure:

	let product = sneakers[indexPath.row]
guard let cell = tableView.dequeueReusableCell(withIdentifier: &quot;ExampleCell&quot;) as? ExampleCell else {
print(&quot;I&#39;ll never print&quot;)
return ExampleCell()
}
print(&quot;Utilize cells&quot;)
cell.configure(product: product)
// configure the closure
cell.removeMe = { [weak self] aCell in
guard let self = self,
let idxPath = self.tableView.indexPath(for: aCell)
else { return }
print(&quot;Update data and remove cell from table view...&quot;)
self.sneakers.remove(at: idxPath.row)
self.tableView.deleteRows(at: [idxPath], with: .automatic)
}
return cell

As a side note -- don't use guard let ... when dequeuing a cell:

	// don&#39;t do it like this
//guard let cell = tableView.dequeueReusableCell(withIdentifier: &quot;ExampleCell&quot;) as? ExampleCell else {
//	print(&quot;I&#39;ll never print&quot;)
//	return ExampleCell()
//}
// dequeue the cell like this
let cell = tableView.dequeueReusableCell(withIdentifier: &quot;ExampleCell&quot;, for: indexPath) as! ExampleCell

If you have incorrectly registered your table view cells, you want the app to crash so you can fix the issue.

huangapple
  • 本文由 发表于 2023年3月8日 19:07:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75672215.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定