-1

I am building my first iOS-App using Swift and I am stuck. I have a CollectionView and inside one of the Cells there is a button and an imageView. What should happen is: I click the button and the imageView shows another picture. I already created a CellSubClass but I just don't get how to use it. Can anyone PLEASE help me?

1 Answers1

1

Write an action method for your button inside your cellClass like this:

func changeImage
{
     var image: UIImage = UIImage(named: "your image name")!
     yourImageView.image = image
}

Don't forget to "assign" this method to your button either in initialization method for the cell (awakeFromNib is also called when cell is started or oyu could write your own custom init method). You can also do it by using IBAction from storyboard (Simple dragging and clicking).

But programmatically it is done Like this if you use the awakeFromNib approach:

override func awakeFromNib() {
        super.awakeFromNib()
        yourButton.addTarget(self, action: "changeImage", forControlEvents: UIControlEvents.TouchUpInside)
    }

To learn how to create IBAction using storyboard, read here.

NSNoob
  • 5,548
  • 6
  • 41
  • 54
  • First of all: Thank you! My problem is: inside of the button func in the CollectionView (which is inside a container) is an if-Loop, which has three cases. Each of these cases needs a different image in the imageView. I could write the if-Classes inside the Cell-SubClass, BUT they refer to the parent ViewController. Is there any way to solve this? – W. Schröder Nov 26 '15 at 15:52
  • I found a way to solve the if-problem. So thank you, you solved my problem! ;) – W. Schröder Nov 26 '15 at 16:02