Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

Retain button state inside collection view when moved to another view controller in swift

I have a button which works as favorite. This button is inside the collection view.The button has 2 states.one selected and unselected.The images changes accordingly for the button. I have achieved the image change for the button inside collection view. The code is given below:

 @objc func favBtnAction(_ sender: UIButton) {
      //  print("inside favbtnaction",sender.tag,self.likedIdArray,self.finalidArray1)
        
        if boolarray1[sender.tag]{
             print("1")
            let userid = String(describing:  self.finalidArray1[sender.tag])
              boolarray1[sender.tag] = false
             
              if let image = UIImage(named: "fav") {
                                   sender.setImage(image, for: .normal)
                              }
            removefavservice(id:userid)
          }else{
               print("2")
            let userid = String(describing:  self.finalidArray1[sender.tag])
              boolarray1[sender.tag] = true
             
              if let image = UIImage(named: "fav_filled") {
                                   sender.setImage(image, for: .normal)
                              }
            
            addfavservice(id:userid)

          }
}

Inside the collection view,the code for favorite button is as follows:

  cell.favBtn.tag = indexPath.row
                cell.favBtn.isUserInteractionEnabled = true
                cell.favBtn.addTarget(self, action: #selector(favBtnAction), for: .touchUpInside)

if boolarray1[indexPath.row]{
              
              if let image = UIImage(named: "fav_filled") {
                cell.favBtn.setImage(image, for: .normal)
                               }

            }else{
             
                if let image = UIImage(named: "fav") {
                cell.favBtn.setImage(image, for: .normal)
  
           }
            }
        

But when i goto another view controller and come back to same view controller, the state is not maintained.How to achieve this?Please help me out.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...