Not able to change view colour in UICollection view

90 views Asked by At

I am trying to change colour of the view inside the uicollectionviewcell. But I am not able to change the colour. When I try to connect to the UIViewController to our view controller it say " cannot connect the repetitive content as an outlet.".

When I change the background of the cell it comes like this enter image description here

As to make it round I am using view and the giving it layer radius properties.

What I am trying to achieve is: enter image description here

The values are coming from the model class that I have created and assigned it to UIcolectionviewcell. Model contains only one text field that shows the tags.

When user select any tags the background and text colour will change.I am not to achieve this. It might be easy to do but somehow I am not able to achieve this.

2

There are 2 answers

0
Francesco Destino On

Try to change the background color of your rounded element and not of the entire cell You can create custom UICollectionViewCell and use it to access different items inside of it, like the textfield with your tag

0
Natarajan On

I've added the sample code to achieve your requirements, Please refer and try implementing based on the following code:

//Your model class
class TagModel{

    var tag:String!
    var selected:Bool!

    init(tag:String, selected:Bool) {

        self.tag = tag
        self.selected = selected
    }
}

//your cell with Xib
class TagCell:UICollectionViewCell{

    @IBOutlet weak var tagLabel: UILabel!

    override func awakeFromNib() {

        super.awakeFromNib()
    }

    func setTag(_ tagModel:TagModel){

        tagLabel.layer.masksToBounds = true
        tagLabel.layer.cornerRadius = tagLabel.frame.size.height/2

        tagLabel.text = tagModel.tag

        if tagModel.selected{

            tagLabel.textColor = .white
            tagLabel.backgroundColor = .blue
        }else{

            tagLabel.textColor = .gray
            tagLabel.backgroundColor = .lightGray
        }
    }
}

//Your ViewController which has `UICollectionView`
class TagViewController:UIViewController, UICollectionViewDelegate, UICollectionViewDataSource{

    var tagModels:[TagModel]!

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        tagModels[indexPath.item].selected = !tagModels[indexPath.item].selected

        collectionView.reloadItems(at: [indexPath])
    }
}

Note: Please take this code as sample and make modifications based on your implementations.