How to get Cell title from external data source for UICollectionView

喜你入骨 提交于 2020-01-06 06:09:28

问题


I currently have a view where I display a collectionView with some categories. I followed this post to get my collectionView to properly load display data. I got that working just fine.

My issue is that now I need to be able to get the text from whichever cell the user selects to use within my search bar.

My current code:

class SearchViewController: ButtonBarPagerTabStripViewController, UISearchBarDelegate{

    let headerId = "sectionHeader"
    let categoriesId = "categoriesId"

    lazy var searchBar: UISearchBar = {
        let sb = UISearchBar()
        sb.placeholder = "Search businesses or coupons"
        sb.barTintColor = .gray
        UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).backgroundColor = UIColor.mainWhite()
        sb.delegate = self
        return sb
    }()

    lazy var searchCategriesView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.headerReferenceSize = CGSize(width: view.frame.width, height: 75)
        layout.itemSize = CGSize(width: view.frame.width, height: 50)
        layout.minimumInteritemSpacing = 1
        layout.minimumLineSpacing = 1
        layout.scrollDirection = .vertical
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = UIColor.mainWhite()
        cv.translatesAutoresizingMaskIntoConstraints = false
        return cv
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        categoriesDataSource = SearchCategories()
        searchCategriesView.dataSource = categoriesDataSource

        searchCategriesView.register(SearchCategoriesCell.self, forCellWithReuseIdentifier: categoriesId)
        searchCategriesView.register(SectionHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerId)
    }

    //EXCLUDED VIEW SETUP CODE FOR BREVITY
}

And as per the link mentioned above, I set up my data source in another file like this:

class SearchCategories: NSObject {
    let categories = ["Apparel & Clothing", "Arts & Crafts", "Automotive",
                      "Baby", "Bars & Lounges", "Beauty", "Books",
                      "Entertainment",
                      "Family & Children", "Furniture",
                      "Grocery",
                      "Health", "Home & Garden", "Home improvement",
                      "Pets", "Pizza",
                      "Restaurants",
                      "Sporting Goods"]

    let headerId = "sectionHeader"
    let categoriesId = "categoriesId"

    override init() {
    }
}


extension SearchCategories: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return categories.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: categoriesId, for: indexPath) as! SearchCategoriesCell
        cell.label.text = categories[indexPath.item]
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

        let sectionHeaderView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerId, for: indexPath) as! SectionHeaderView

        if indexPath.section == 0 {
            sectionHeaderView.categoryTitleLabel.text = "Search Categories"
        }
        return sectionHeaderView
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: categoriesId, for: indexPath) as! SearchCategoriesCell
        //NEED TO PASS THIS DATA BACK TO SEARCHVIEWCONTROLLER
    }
}

How do I now get the cell text back in the SearchViewController whenever a user clicks on a collectionView cell?


回答1:


Suppose you will hold the text in this function inside SearchViewController

func send(_ res:String){
  print(res)
}

1- Add a var inside

class SearchCategories: NSObject {

  weak var delegate:SearchViewController?

2- Set the delegate

categoriesDataSource = SearchCategories()
categoriesDataSource.delegate = self

3- Send the clicked text

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
   let sendedText =  categories[indexPath.item]
   delegate?.send(sendedText)
}

Edit: You need to add

searchCategriesView.delegate = categoriesDataSource

in viewDidLoad also you can do

searchCategriesView.delegate = self

and implement the didSelectItemAt inside SearchViewController



来源:https://stackoverflow.com/questions/53254177/how-to-get-cell-title-from-external-data-source-for-uicollectionview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!