简体   繁体   中英

Finding and deleting a video from UICollectionView with Button - Swift

Problem: I can't find which delete button that I pressed and tie that to the video in the cell so I can delete it on Parse.

I added a button programmatically in the cellForIndexAtIndexPath

self.deleteButton = UIButton(frame: CGRectMake(cell.frame.size.width / 1.5, 10, 30, 30))
let deleteImage = UIImage(named: "deleteVideoButton.png")
self.deleteButton.setBackgroundImage(deleteImage, forState: .Normal)
self.deleteButton.tag = indexPath.row
self.deleteButton.addTarget(self, action: "deleteCellFromButton", forControlEvents: UIControlEvents.TouchUpInside)
cell.addSubview(self.deleteButton)

The buttons show up on each cell display in the UICollectionView.
I have a function that calls the deleteCellFromButton(). I know that I should use the index.path but I can't call it in this function.

func deleteCellFromButton() {

    var alert = UIAlertController(title: "Are you sure?", message: "This video will be deleted forever", preferredStyle: UIAlertControllerStyle.ActionSheet)

    let confirmAction : UIAlertAction = UIAlertAction(title: "Ok!", style: .Default) { (action) -> Void in

        var query = PFQuery(className: "Movie")
        query.whereKey("username", equalTo: (PFUser.currentUser()?.username)!) 

// here is where I think this goes query.whereKey("videoFile", equalTo: self.videoArray[index.path.row]) ???



        query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in

            if error != nil {

                print(error)

            } else {

                for object in objects! {
                    print(object)

                    object.deleteInBackgroundWithBlock({ (success: Bool, error: NSError? ) -> Void in

                        //put after delete code stuff here.

                    })

                }

            }

        }

    }

    let cancelAction : UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { (error) -> Void in

    }

    alert.addAction(confirmAction)
    alert.addAction(cancelAction)

    self.presentViewController(alert, animated: true, completion: nil)

}

Change your target function to name with : . Here you pass your button to your target function.

self.deleteButton.addTarget(self, action: "deleteCellFromButton:", forControlEvents: UIControlEvents.TouchUpInside)

And in your function use your button.tag :

func deleteCellFromButton(button: UIButton) {
    println(button.tag)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM