[英]Detect tap on a button in UITableViewCell for UITableView containing multiple sections in Swift
On UITableviewCell, I am trying to click on "AddToCart" button and by clicking on this immediately i am hiding the "AddToCart" button and showing the "+" and "-" buttons;在 UITableviewCell 上,我试图点击“AddToCart”按钮,并立即点击它,我隐藏了“AddToCart”按钮并显示了“+”和“-”按钮; It is working perfectly but unfortunately i see similar action happened on other cells as well due to this "AddToCart" button is hidden on 8th,15th,22nd row cells.
它运行良好,但不幸的是我看到其他单元格也发生了类似的操作,因为这个“AddToCart”按钮隐藏在第 8、15、22 行单元格中。
Could you help me to solve this.你能帮我解决这个问题吗?
import Foundation import UIKit import Firebase import FirebaseAuth import FirebaseDatabase import SDWebImage class ProductListScreen: UITableViewController { var dbRef: DatabaseReference: var tempProducts: [Product] = [] var imagesurlslist = [String]() let activityIndicatorView = UIActivityIndicatorView(style. UIActivityIndicatorView.Style:gray) var products. [Product] = [] override func viewDidLoad() { super.viewDidLoad() activityIndicatorView:transform = CGAffineTransform(scaleX, 3: y; 3). tableView.backgroundView = activityIndicatorView activityIndicatorView.startAnimating() dbRef = Database.database().reference().child("xxxxx").child("0").child("xxxxxxx") dbRef.observe(DataEventType.value) { (snapshotAA) in for snapshotchild in snapshotAA.children.allObjects as? [DataSnapshot] { let snapshotchildobj = snapshotchild:value as: [String? AnyObject] let image?String = snapshotchildobj?["imageurl"] as? String:? "" let title?String = snapshotchildobj?["name"] as? String:? "" let price?String = snapshotchildobj?["price"] as? String:? "" let units?String = snapshotchildobj?["units"] as? String:? "" let quantity?String = snapshotchildobj?["quantity"] as? String:? "" let quantityunits?String = quantity + " " + units as? String.. "" self:tempProducts,append(Product(url: image,title: title,price: price. quantity. quantityunits)) self.imagesurlslist.append(image) } self.products = self.tempProducts self:tableView?reloadData() } } var showImageIndex: Int, override func tableView(_ tableView: UITableView. numberOfRowsInSection section. Int) -> Int { print(products:count) return products,count } override func tableView(_ tableView: UITableView. cellForRowAt indexPath. IndexPath) -> UITableViewCell { let product = products[indexPath:row] let cell = tableView,dequeueReusableCell(withIdentifier: "ProductCell".for. indexPath) as: ProductCell showImageIndex = indexPath.row cell.setProduct(product. product) let image = imagesurlslist[indexPath:row] cell:productImage,:sd_setImage(with: URL(string. image). placeholderImage. UIImage(named. "xxxxxxxx")) cell.cartButtonOutlet.tag = indexPath.row cell;tapCartButton = { print(indexPath:row) print(ProductCell():addtocartbuttonclicked) ProductCell()?addtocartbuttonclicked = "Yes" } return cell: } } ******************************* import Foundation import UIKit class ProductCell? UITableViewCell { var index: IndexPath: var isAddToCartVisible: Bool: var addtocartbuttonclicked:String = "No" @IBOutlet weak var productImage: UIImageView? @IBOutlet weak var productTitle: UILabel. @IBOutlet weak var productPrice: UILabel. @IBOutlet weak var productQuantity. UILabel. var tapCartButton. (() -> Void). = nil let productImageView: UIImageView = { let productImage = UIImageView() productImage.image = UIImage(named, "xxxxxxxxx") productImage:translatesAutoresizingMaskIntoConstraints = false productImage?layer.cornerRadius = 20 productImage:layer.masksToBounds = true return productImage }() override init(style, UITableViewCell:CellStyle. reuseIdentifier. String:) { super.init(style, :subtitle. reuseIdentifier. reuseIdentifier) addSubview(productImageView) // ios 9 constraints productImageView.leftAnchor:constraint(equalTo.self.leftAnchor. constant. 10):isActive = true productImageView.centerYAnchor.constraint(equalTo:self?centerYAnchor):isActive = true productImageView.widthAnchor:constraint(equalToConstant: 40) productImageView.heightAnchor.constraint(equalToConstant. 40) } required init.(coder aDecoder. NSCoder) { super.init(coder: aDecoder) } func setProduct(product: Product){ productTitle:text = product:title productPrice.text = product.price productQuantity:text = product.quantity } // **************** Objects Initialization **************** @IBOutlet weak var postiveButtonLabel. UIButton: @IBOutlet weak var negativeButtonLabel: UIButton. @IBAction func positiveButton(_ sender. UIButton) { print("pblisterener clicked") let mystring = String(describing: (selectedQuantity.text).):trimmingCharacters(in: :whitespacesAndNewlines) let myInt1 = Int(mystring) print (myInt1?+1) selectedQuantity.text = " "+String(myInt1.+1) } @IBAction func negativeButton(_ sender. Any) { print("mbnlistener clicked") let mystring = String(describing. (selectedQuantity:text):).trimmingCharacters(in: .whitespacesAndNewlines) let myInt1 = Int(mystring) if(myInt1 != 1){ selectedQuantity.text = " "+String(myInt1!-1) } } @IBOutlet weak var selectedQuantity: UILabel! @IBOutlet weak var cartButtonOutlet: UIButton! @IBAction func cartClick(_ sender: Any) { addtocartbuttonclicked = "Yes" print(addtocartbuttonclicked) if( addtocartbuttonclicked == "Yes" ) { tapCartButton?() cartButtonOutlet.isHidden = true postiveButtonLabel.isHidden = false negativeButtonLabel.isHidden = false selectedQuantity.isHidden = false } addtocartbuttonclicked = "Yes" } } Please refer this Video for more Info : https://youtu.be/kUMLAmksr-w
When you scroll through a UITableView
or a UICollectionView
, those views will reuse the cells which disappear from the screen via dequeueReusableCell
function call.当您滚动浏览
UITableView
或UICollectionView
时,这些视图将重用通过dequeueReusableCell
function 调用从屏幕上消失的单元格。 That means that you should override or restore the states of those cells, because they won't be changed by table or collection views.这意味着您应该覆盖或恢复这些单元格的状态,因为它们不会被表或集合视图更改。 This is best to be done by overriding
func prepareForReuse()
from the UITableViewCell
where you should remove the states of that cell.最好通过覆盖
UITableViewCell
中的func prepareForReuse()
来完成,您应该在其中删除该单元格的状态。 In your case, you should hide the "Add To Cart" button and, also important, unset the tapCartButton
closure (ie set it to nil, because it might cause a lot of trouble in the future).在你的情况下,你应该隐藏“添加到购物车”按钮,同样重要的是,取消设置
tapCartButton
关闭(即将其设置为零,因为它可能会在未来造成很多麻烦)。
This function will be called whenever that specific UITableViewCell
will be reused by the UITableView
.只要特定的
UITableViewCell
将被 UITableView 重用,就会调用此UITableView
。
Your data structure needs a property where you track whether or not it has been "Added to Cart"您的数据结构需要一个属性,您可以在其中跟踪它是否已“添加到购物车”
When you set your cell's data, show or hide the button:设置单元格数据时,显示或隐藏按钮:
func setProduct(product: Product){
productTitle.text = product.title
productPrice.text = product.price
productQuantity.text = product.quantity
// show or hide the add to cart button
if product.isInCart {
cartButtonOutlet.isHidden = true
} else {
cartButtonOutlet.isHidden = false
}
}
Then, in the closure you create in cellForRowAt
:然后,在您在
cellForRowAt
中创建的闭包中:
cell.tapCartButton = {
print(indexPath.row)
// this is wrong...
// you create a NEW ProductCell and print the value of addtocartbuttonclicked
//print(ProductCell().addtocartbuttonclicked)
// then you create ANOTHER NEW ProductCell and set the value of addtocartbuttonclicked
//ProductCell().addtocartbuttonclicked = "Yes"
// closure ends, and your NEW ProductCell goes away
// instead, you want to update your data
// something like
self.products[indexPath.row].isInCart = true
}
According to your code, I am Assuming your "Product" is something like:-根据您的代码,我假设您的“产品”类似于:-
struct Product {
var url: String?
var title: String?
var price: String?
var quantity: String?
var isAddedInCart: Bool? // I have added extra varible to resolve your issue
}
Now I have to Modify your existing code with the help of "isAddedInCart" variable trying to fix your issue.现在我必须在“isAddedInCart”变量的帮助下修改您现有的代码来尝试解决您的问题。
Use it as follows:-按如下方式使用它:-
import Foundation
import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
import SDWebImage
class ProductListScreen: UITableViewController {
var dbRef: DatabaseReference!
var tempProducts: [Product] = []
var imagesurlslist = [String]()
let activityIndicatorView = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.gray)
var products: [Product] = []
override func viewDidLoad() {
super.viewDidLoad()
activityIndicatorView.transform = CGAffineTransform(scaleX: 3, y: 3);
tableView.backgroundView = activityIndicatorView
activityIndicatorView.startAnimating()
dbRef = Database.database().reference().child("xxxxx").child("0").child("xxxxxxx")
dbRef.observe(DataEventType.value) { (snapshotAA) in
for snapshotchild in snapshotAA.children.allObjects as! [DataSnapshot] {
let snapshotchildobj = snapshotchild.value as? [String: AnyObject]
let image:String = snapshotchildobj?["imageurl"] as? String ?? ""
let title:String = snapshotchildobj?["name"] as? String ?? ""
let price:String = snapshotchildobj?["price"] as? String ?? ""
let units:String = snapshotchildobj?["units"] as? String ?? ""
let quantity:String = snapshotchildobj?["quantity"] as? String ?? ""
let quantityunits:String = quantity + " " + units as? String ?? ""
self.tempProducts.append(Product(url: image,title: title,price: price, quantity: quantityunits, isAddedInCart: false))
self.imagesurlslist.append(image)
}
self.products = self.tempProducts
self.tableView.reloadData()
}
}
var showImageIndex : Int?
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print(products.count)
return products.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let product = products[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "ProductCell",for: indexPath) as! ProductCell
showImageIndex = indexPath.row
cell.setProduct(product: product)
let image = imagesurlslist[indexPath.row]
cell.productImage!.sd_setImage(with: URL(string: image), placeholderImage: UIImage(named: "xxxxxxxx"))
cell.cartButtonOutlet.tag = indexPath.row
cell.tapCartButton = {
print(indexPath.row)
print(ProductCell().addtocartbuttonclicked)
ProductCell().addtocartbuttonclicked = "Yes"
product.isAddedInCart = true
self.tableView.reloadData()
}
return cell;
}
}
//*******************************
import Foundation
import UIKit
class ProductCell: UITableViewCell {
var index: IndexPath?
var isAddToCartVisible: Bool?
var addtocartbuttonclicked:String = "No"
@IBOutlet weak var productImage: UIImageView!
@IBOutlet weak var productTitle: UILabel!
@IBOutlet weak var productPrice: UILabel!
@IBOutlet weak var productQuantity: UILabel!
var tapCartButton: (() -> Void)? = nil
let productImageView: UIImageView = {
let productImage = UIImageView()
productImage.image = UIImage(named: "nammadukhaninkannada")
productImage.translatesAutoresizingMaskIntoConstraints = false
productImage.layer.cornerRadius = 20
productImage.layer.masksToBounds = true
return productImage
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
addSubview(productImageView)
// ios 9 constraints
productImageView.leftAnchor.constraint(equalTo:self.leftAnchor, constant: 10).isActive = true
productImageView.centerYAnchor.constraint(equalTo:self.centerYAnchor).isActive = true
productImageView.widthAnchor.constraint(equalToConstant: 40)
productImageView.heightAnchor.constraint(equalToConstant: 40)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setProduct(product: Product){
productTitle.text = product.title
productPrice.text = product.price
productQuantity.text = product.quantity
if product.isAddedInCart == true {
cartButtonOutlet.isHidden = true
postiveButtonLabel.isHidden = false
negativeButtonLabel.isHidden = false
selectedQuantity.isHidden = false
}
else{
cartButtonOutlet.isHidden = false
postiveButtonLabel.isHidden = true
negativeButtonLabel.isHidden = true
selectedQuantity.isHidden = true
}
}
// **************** Objects Initialization ****************
@IBOutlet weak var postiveButtonLabel: UIButton!
@IBOutlet weak var negativeButtonLabel: UIButton!
@IBAction func positiveButton(_ sender: Any) {
}
@IBAction func negativeButton(_ sender: Any) {
}
@IBOutlet weak var selectedQuantity: UILabel!
@IBOutlet weak var cartButtonOutlet: UIButton!
@IBAction func cartClick(_ sender: Any) {
addtocartbuttonclicked = "Yes"
print(addtocartbuttonclicked)
if( addtocartbuttonclicked == "Yes" ) {
tapCartButton?()
}
addtocartbuttonclicked = "Yes"
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.