我正在开发一个 iOS 项目,我的
UITableView
遇到了问题。我无法阻止表格视图在向下滚动时刷新单元格数据。我使用 Core Data 来管理和获取我的数据。
在表格视图中,每个单元格都有一个用于添加项目的 (+) 按钮。点击此按钮也会更改单元格的颜色。然而,当我向下滚动时,单元格刷新并且它们的状态重置,这意味着颜色变化和其他动态状态丢失。
添加ShoppingItemTableViewCell:
import UIKit
// MARK: - PantryTableViewCellDelegate
protocol AddShoppingItemTableViewCellDelegate: AnyObject {
func addButtonTapped(shoppingSubItem: Shopping_Sub_List)
func editButtonTapped(shoppingSubItem: Shopping_Sub_List)
}
class AddShoppingItemTableViewCell: UITableViewCell {
@IBOutlet weak var addToListButton: UIButton!
@IBOutlet weak var itemNameLabel: UILabel!
@IBOutlet weak var categoryLabel: UILabel!
@IBOutlet weak var editButton: UIButton!
weak var delegate: AddShoppingItemTableViewCellDelegate?
var shoppingSubItem: Shopping_Sub_List?
override func awakeFromNib() {
super.awakeFromNib()
itemNameLabel.font = UIFont(name: Global.Inter_Medium_500, size: 17.0)
categoryLabel.font = UIFont(name: Global.Inter_Medium_500, size: 17.0)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
// MARK: - Action
// add To List Button Action
@IBAction func addToListButtonAction(_ sender: UIButton) {
guard let shoppingSubItem = shoppingSubItem else { return }
addToListButton.setImage(UIImage(named: "Added"), for: .normal)
delegate?.addButtonTapped(shoppingSubItem: shoppingSubItem)
}
// edit Button Action
@IBAction func editButtonAction(_ sender: UIButton) {
guard let shoppingSubItem = shoppingSubItem else { return }
delegate?.editButtonTapped(shoppingSubItem: shoppingSubItem)
}
// MARK: Cell Configuration
// configure The Cell
func configureTheCell(_ shoppingSubList: Shopping_Sub_List) {
self.shoppingSubItem = shoppingSubList
itemNameLabel.text = shoppingSubList.name
categoryLabel.text = "in \(shoppingSubList.category ?? "Uncategorized")"
}
}
添加购物项目VC:
import UIKit
import CoreData
class AddShoppingItemsVC: UIViewController {
// MARK: - IBOutlet
@IBOutlet weak var addItemSearchBar: UISearchBar!
@IBOutlet weak var microphoneButton: UIButton!
@IBOutlet weak var addShoppingItemTableView: UITableView!
var shoppingList: Shopping_List?
let coreDataHelper = CoreDataHelper()
var allShoppingSubLists: [Shopping_Sub_List]?
var filteredShoppingSubLists: [Shopping_Sub_List]?
override func viewDidLoad() {
super.viewDidLoad()
addItemSearchBar.delegate = self
addShoppingItemTableView.delegate = self
addShoppingItemTableView.dataSource = self
addShoppingItemTableView.register(UINib(nibName: "AddShoppingItemTableViewCell", bundle: nil),
forCellReuseIdentifier: Global.AddShoppingItemTableViewCellIdentifier)
addShoppingItemTableView.register(UINib(nibName: "AddItemTableViewCell", bundle: nil),
forCellReuseIdentifier: Global.AddItemTableViewCellIdentifier)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.isNavigationBarHidden = false
self.navigationController?.navigationBar.prefersLargeTitles = false
fetchAllShoppingSubLists()
addItemSearchBar.text = ""
addShoppingItemTableView.reloadData()
}
// MARK: - Function
// Function to fetch all shopping sub-lists
func fetchAllShoppingSubLists() {
if let shoppingSubLists = coreDataHelper.fetchAllShoppingSubListData() {
self.allShoppingSubLists = shoppingSubLists.sorted { $0.name ?? "" < $1.name ?? "" }
self.filteredShoppingSubLists = shoppingSubLists.sorted { $0.name ?? "" < $1.name ?? "" }
} else {
print("Error fetching shopping sub-lists")
}
}
// MARK: - Action
// microphone Button Action
@IBAction func microphoneButtonAction(_ sender: UIButton) {
print("microphoneButtonAction")
}
}
extension AddShoppingItemsVC: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (filteredShoppingSubLists?.count ?? 0) + 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == (filteredShoppingSubLists?.count ?? 0) {
// This is the last cell
if let cell = tableView.dequeueReusableCell(withIdentifier: Global.AddItemTableViewCellIdentifier,
for: indexPath) as? AddItemTableViewCell {
cell.delegate = self
return cell
}
} else {
// Regular cells for shopping sub lists
if let cell = tableView.dequeueReusableCell(withIdentifier: Global.AddShoppingItemTableViewCellIdentifier,
for: indexPath) as? AddShoppingItemTableViewCell {
guard let shoppingSubLists = filteredShoppingSubLists?[indexPath.row] else { return cell}
cell.configureTheCell(shoppingSubLists)
cell.delegate = self
return cell
}
}
return UITableViewCell()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 56
}
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let editAction = UIContextualAction(style: .normal, title: "Remove") { [weak self] (_, _, completionHandler) in
self?.deleteActionForRow(at: indexPath)
completionHandler(true)
}
editAction.backgroundColor = UIColor(named: "DeleteAction")
return UISwipeActionsConfiguration(actions: [editAction])
}
// edit Action For Row
private func deleteActionForRow(at indexPath: IndexPath) {
print(indexPath)
}
}
// MARK: - AddShoppingItemTableViewCellDelegate
extension AddShoppingItemsVC: AddShoppingItemTableViewCellDelegate {
func editButtonTapped(shoppingSubItem: Shopping_Sub_List) {
let vc = storyboard?.instantiateViewController(identifier: Global.EditItemViewControllerIdentifier) as! EditItemViewController
vc.selectedShoppingSubList = shoppingSubItem
vc.parentList = shoppingList
vc.isSavaItem = false
self.navigationController?.pushViewController(vc, animated: true)
}
func addButtonTapped(shoppingSubItem: Shopping_Sub_List) {
guard let shoppingLists = shoppingList else { return }
coreDataHelper.addShoppingSubListToItemsList(subList: shoppingSubItem, parentList: shoppingLists)
}
}
// MARK: - UISearchBarDelegate
extension AddShoppingItemsVC: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.isEmpty {
filteredShoppingSubLists = allShoppingSubLists
} else {
filteredShoppingSubLists = allShoppingSubLists?.filter { $0.name?.lowercased().contains(searchText.lowercased()) ?? false }
}
addShoppingItemTableView.reloadData()
}
}
// MARK: - AddItemTableViewCellDelegate
extension AddShoppingItemsVC: AddItemTableViewCellDelegate {
func addButtonTapped() {
let vc = storyboard?.instantiateViewController(identifier: Global.EditItemViewControllerIdentifier) as! EditItemViewController
vc.isSavaItem = true
self.navigationController?.pushViewController(vc, animated: true)
}
}
向下滚动时,我无法阻止
UITableView
刷新单元格数据。我使用核心数据来获取并显示所有购物清单(名称)。当我点击 addButtonTapped
时,所有单元格都有一个 (+) 按钮来添加项目。点击此按钮也会更改单元格的颜色。但是,当我向下滚动时,单元格会自动刷新。我想阻止这种事发生。
根据您从模型中获得的详细信息,我假设了模型并创建了一个模型。在模型中,你必须传递你的密钥,正如我下面提到的。
struct Shopping_Sub_List {
var name,category: String?
//Here you need to add bool in your model to track button updated value.
var isAdded = false
}
AddShoppingItemTableViewCell
:
func configureTheCell(_ shoppingSubList: Shopping_Sub_List) {
self.shoppingSubItem = shoppingSubList
itemNameLabel.text = shoppingSubList.name
categoryLabel.text = "in \(shoppingSubList.category ?? "Uncategorized")"
//Here you get dynamic state and based button image based on your value get.
addToListButton.setImage(shoppingSubList.isAdded ? UIImage(named: "Added") : UIImage(named: "Add"), for: .normal)
}
// add To List Button Action
@IBAction func addToListButtonAction(_ sender: UIButton) {
guard let shoppingSubItem = shoppingSubItem else { return }
//Here you update your value and passed to the delegate.
shoppingSubItem.isAdded = true
addToListButton.setImage(UIImage(named: "Added"), for: .normal)
delegate?.addButtonTapped(shoppingSubItem: shoppingSubItem)
}
使用此功能,您可以获得动态状态并相应地进行管理。