Xcode9 Swift4:为UICollectionView添加标签按钮及动态数据过滤功能
Got it, let's walk through how to implement this step by step. I'll break it down into manageable parts so you can follow along easily.
1. Conditionally Load Your Tag Data at Runtime
First, instead of hardcoding the tags array directly, create a method that returns the appropriate list based on your specific conditions. This way, you can dynamically adjust which tags are shown when the view loads (or whenever your conditions change).
For example:
// Define your original full tag list private let allTags = ["Appointments", "Waitlisted", "Suspended", "Billing", "Cancelled", "Transfer", "Revoked", "Checkedin"] // Function to get filtered tags based on your conditions private func getConditionalTags() -> [String] { // Replace this with your actual condition check (e.g., user permissions, app state) let userHasBillingAccess = true let userCanViewTransfers = false var filteredTags = allTags if !userHasBillingAccess { filteredTags.removeAll { $0 == "Billing" } } if !userCanViewTransfers { filteredTags.removeAll { $0 == "Transfer" } } return filteredTags }
Then, in your view controller, store this conditional array as a property to use in the collection view data source:
private var currentTags: [String] = [] override func viewDidLoad() { super.viewDidLoad() // Load tags based on conditions when the view loads currentTags = getConditionalTags() // Reload collection view to show the dynamic tags collectionView.reloadData() }
2. Set Up UICollectionView Data Source & Delegate
Make sure your collection view uses the currentTags array for its data. Also, implement the selection handler to trigger the table view filtering, plus add visual feedback for the selected tag.
First, create a simple collection view cell class (if you haven't already):
class TagCell: UICollectionViewCell { @IBOutlet weak var tagLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() layer.cornerRadius = 16 layer.masksToBounds = true } }
Then implement the collection view data source and delegate in your view controller:
// MARK: - UICollectionView Data Source extension YourViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return currentTags.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TagCell", for: indexPath) as! TagCell let tag = currentTags[indexPath.item] cell.tagLabel.text = tag // Highlight selected tag for visual feedback cell.backgroundColor = (selectedTag == tag) ? .systemBlue : .systemGray5 cell.tagLabel.textColor = (selectedTag == tag) ? .white : .black return cell } } // MARK: - UICollectionView Delegate extension YourViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let selectedTag = currentTags[indexPath.item] self.selectedTag = selectedTag // Store selected tag as a property // Filter table view data and refresh filterTableViewData(for: selectedTag) // Refresh collection view to update selected tag appearance collectionView.reloadData() } }
3. Filter & Update Your TableView
You'll need two arrays for your table view: one with the original unfiltered data, and another with the filtered results. When a tag is selected, filter the original array based on the tag value and reload the table view.
// Properties for table view data private var originalTableData: [YourDataModel] = [] // Replace with your actual data model private var filteredTableData: [YourDataModel] = [] private var selectedTag: String? // Function to load your original table data (replace with your data fetch logic) private func loadOriginalTableData() { // Example: Fetch from API, Core Data, etc. originalTableData = [ YourDataModel(name: "John Doe", status: "Appointments"), YourDataModel(name: "Jane Smith", status: "Waitlisted"), YourDataModel(name: "Bob Brown", status: "Billing") ] } // Function to filter data based on selected tag private func filterTableViewData(for tag: String) { // Replace this with your actual filtering logic matching your data model filteredTableData = originalTableData.filter { item in return item.status == tag // Assuming your model has a "status" property matching the tags } // Refresh the table view to show filtered results tableView.reloadData() }
Don't forget to update your table view data source to use filteredTableData:
// MARK: - UITableView Data Source extension YourViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return filteredTableData.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "YourTableCell", for: indexPath) as! YourTableCell let item = filteredTableData[indexPath.row] // Configure your cell with the item data (e.g., cell.nameLabel.text = item.name) return cell } }
4. Handle Initial State
If you want to show all data when no tag is selected, initialize filteredTableData with originalTableData in viewDidLoad:
override func viewDidLoad() { super.viewDidLoad() // Load original table data loadOriginalTableData() // Show all data initially filteredTableData = originalTableData tableView.reloadData() // Load conditional tags and refresh collection view currentTags = getConditionalTags() collectionView.reloadData() }
This should cover all your requirements: conditional tag loading at runtime, tag selection handling with visual feedback, and table view filtering with immediate refresh. Let me know if you need help with any specific edge case!
内容的提问来源于stack exchange,提问作者JoJo

