Search code examples
iosswift2xcode7iboutlet

Access an IBOutlet from another class


I have 2 swift files the one is my HomeViewController and the second is my EventCollectionViewCell. In the second one I have an IBOutlet = informationView :UIView and I want to access this from the HomeViewController.

Is there any way ? Thank you in advance, KS


Solution

  • Well I suppose that in HomeViewController you have a UICollectionView and that acts as a datasource for it, then in your collectionView dataSource you can make:

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cellIdentifier", forIndexPath: indexPath) as! EventCollectionViewCell
    
        //Here you can access the IBOulets define in your cell
        cell.informationView.backgroundColor = UIColor.greenColor()
    
        return cell
    }
    

    Edit:

    Problem: When you tap on a cell you want to show an Overlay inside the cell.

    Solution: You need you data model to maintain the state, if it's active or not (the informationView), suppose that ItemCell is my model (in your case Event can be):

    class ItemCell{
        var active:Bool = false
    }
    

    In the collectionView:cellForRowAtIndexPath:, you're going to check the current status of your model, and base on that, show or hide that overlay:

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cellIdentifier", forIndexPath: indexPath) as! EventCollectionViewCell
    
        let event = self.data[indexPath.row]
        //Here you can access the IBOulets define in your cell
        cell.informationView.hidden = !event.active
    
        return cell
    }
    

    Then as a final step, every time you select a cell (func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) method), you're going to update the status of your model:

    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath){
        let event = self.data[indexPath.row]
        event.active = !event.active
        collectionView.reloadData()
    }
    

    Sample Project: https://github.com/Abreu0101/SampleTap