How do I use the expand detail button in a UICollectionViewCell?

I am trying to use the expand detail button on the view controller pictured below (PhotoSearchViewController) to show a UIAlertController that shows the description of a photo from an ImageUrlItem.

enter image description here

When I click the button, it shows that it was clicked, but the warning that contains the description is not displayed.

My code for ImageUrlItem:

    import Foundation
import Firebase

struct ImageUrlItem {


    //Should I add my description in here?
    let key: String
    let imageUrl: String
    let watsonCollectionImageUrl: String
    let score: Double
    let description: String

    let ref: FIRDatabaseReference?

    init(imageUrl: String, key: String = "", watsonCollectionImageUrl: String = "", score: Double = 0, description: String) {
        self.key = key
        self.imageUrl = imageUrl
        self.watsonCollectionImageUrl = watsonCollectionImageUrl
        self.ref = nil
        self.score = score
        self.description = description
    }

    init(snapshot: FIRDataSnapshot) {
        key = snapshot.key
        let snapshotValue = snapshot.value as! [String: AnyObject]
        imageUrl = snapshotValue["ImageUrl"] as! String // must map to firebase names
        watsonCollectionImageUrl = ""
        score = 0
        description = snapshotValue["Description"] as! String

        ref = snapshot.ref
    }

    func toAnyObject() -> Any {
        return [
            "imageUrl": imageUrl,
            "Description": description
        ]
    }

}

      

My code for a collection view cell (PhotoCell) looks like this:

class PhotoCell: UICollectionViewCell, UIAlertViewDelegate
{

    var photos: [ImageUrlItem] = []
    var ref = FIRDatabase.database().reference(withPath: "Photos")


    @IBOutlet weak var imgPhoto: UIImageView!

    @IBOutlet weak var lblScore: UILabel!

    @IBAction func btnDesc(_ sender: UIButton)
    {
        let alertTitle = "Description"
        let alertMessage = photos.description 

        let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertControllerStyle.alert)
        let okAction = UIAlertAction(title:"Ok", style: UIAlertActionStyle.default)
        {
            (result : UIAlertAction) -> Void in
            print("OK")
        }

        alertController.addAction(okAction)
        self.parentViewController?.present(alertController, animated: true, completion: nil)
    } 

}

      

Code for cellForRowAt in my PhotoSearchViewController:

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let reuseIdentifier = "PhotoCell"
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! PhotoCell
        cell.backgroundColor = UIColor(red:0.74, green:0.76, blue:0.78, alpha: 1.0)

        // Do any custom modifications you your cell, referencing the outlets you defined in the Custom cell file // if we have a label IBOutlet in PhotoCell we can customize it here

        // on page load when we have no search results, show nothing
        if similarImageUrls.count > 0 {

            //print(indexPath.row)
            //print(similarImageUrls.count)

            if (indexPath.row < similarImageUrls.count){

                let image = self.similarImageUrls[indexPath.row]

                // get image asynchronously via URL
                let url = URL(string: image.imageUrl)


                DispatchQueue.global().async {
                    // make an asynchonorous call to load the image
                    DispatchQueue.main.async {
                        cell.imgPhoto.af_setImage(withURL: url!) // show image using alamofire
                    }
                }
                cell.lblScore.isHidden = false
                cell.lblScore.text = "Score: \(NSString(format: "%.2f", (image.score * 100)) as String)%"
                }
            else
            {
                // show the placeholder image instead
                cell.imgPhoto.image = UIImage(named: "person")
                cell.lblScore.isHidden = true
                cell.lblScore.text = "0.00%"
            }
        }
        else
        {
            // show the placeholder image instead
            cell.imgPhoto.image = UIImage(named: "person")
            cell.lblScore.isHidden = true
            cell.lblScore.text = "0.00%"

            // when we get to the last image, and it is not the first time load
            if (indexPath.row == 8 && !firstTimeSearch){
                // show nothing found alert here
                let ac = UIAlertController(title: "Photo Search Completed!", message:"No macthing photo found!", preferredStyle: .alert)
                ac.addAction(UIAlertAction(title: "OK", style: .default))
                self.present(ac, animated: true)
            }
        }

        return cell
    }

}

      

+3


source to share


1 answer


You can use custom delegate to display alert


  // here is the protocol for creating the delegation:

    protocol BtnDesc : class {
        func btnDecAlert(alertTitle: String, message: String)
    }

      


 class PhotoCell: UICollectionViewCell
    {
        // MARK:- Delegate
         weak var btnDescDelegate : BtnDesc?

        var photos: [ImageUrlItem] = []
        var ref = FIRDatabase.database().reference(withPath: "Photos")


        @IBOutlet weak var imgPhoto: UIImageView!

        @IBOutlet weak var lblScore: UILabel!

        @IBAction func btnDesc(_ sender: UIButton)
        {
            let alertTitle = "Description"
            let alertMessage = photos.description 

           btnDescDelegate?.btnDecAlert(alertTitle: alertTitle, message: alertMessage)


        } 

    }

      




Code for cellForRowAt

in PhotoSearchViewController :

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let reuseIdentifier = "PhotoCell"
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! PhotoCell
            //Mark set the delegate.
            cell.btnDescDelegate  = self
     .....

      


  //conform delegate 
  extension PhotoSearchViewController : BtnDesc {

        func btnDecAlert(alertTitle: String, message: String) {

            let alert = UIAlertController(title: alertTitle, message: message, preferredStyle: .alert)

            let okAction = UIAlertAction(title: "Ok", style: .default, handler: {(_ action: UIAlertAction) -> Void in

                  // here is your action
                    print("OK")

            })

            alert.addAction(okAction)

            self.present(alert, animated: true, completion: nil)
        }

    }

      

+2


source







All Articles