简体   繁体   中英

How to add addTarget for Button in UICollectionView?

I'm a newbie, I have the following problem. There is a screen like this picture. I use UICollectionViewCell for header and I can't addTarget for the blue button in this.

在此处输入图片说明

I can't manage. Could you help me?

class UserProfileVC: UICollectionViewController, UICollectionViewDelegateFlowLayout,UserProfileHeaderDelegate{


    var currentUser: User?
    var userToLoadFromSearchVC: User?

    override func viewDidLoad() {
        super.viewDidLoad()


        // Register cell classes
        self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        // resgiter header class before use
        self.collectionView!.register(UserProfileHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader , withReuseIdentifier: headerIdentifier)
        // back ground color
        self.collectionView?.backgroundColor = .white

        //fetch user data
        if userToLoadFromSearchVC == nil{
            fetchCurrentUserData()
        }


    }



    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }


    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items

        return 0
    }



    // config size for header
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {

        return CGSize(width: view.frame.width, height: 200)
    }

    override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

           // Declare header
        let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerIdentifier, for: indexPath) as! UserProfileHeader

        // set delegate
        header.delegate = self

        if let user = self.currentUser {
            header.user = user
        } else if let userToLoadFromSearchVC = self.userToLoadFromSearchVC {
            header.user = userToLoadFromSearchVC
            self.navigationItem.title = userToLoadFromSearchVC.username

        }
        // Return header

           return header
       }
    override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    }

This is my code in header file.

class UserProfileHeader: UICollectionViewCell {

    var delegate: UserProfileHeaderDelegate?
    var user: User? {
        didSet {
            configuredEditProfileFollowButton()

            setUserStats(for: user)


            let fullName = user?.name
            nameLabel.text = fullName

            guard let profileImageUrl = user?.profileImage else {return}
            profileImageView.loadImage(with:profileImageUrl)
        }
    }

    let  profileImageView : UIImageView  = {
        let iv = UIImageView()
        iv.contentMode = .scaleAspectFill
        iv.clipsToBounds = true
        iv.backgroundColor = .lightGray
        return iv

    }()

    let nameLabel: UILabel = {
       let label = UILabel()
        label.font = UIFont.boldSystemFont(ofSize: 12)
        return label
    }()

    let postLabel: UILabel = {
       let label = UILabel()
        label.numberOfLines = 0
        label.textAlignment = .center

        let attributedText = NSMutableAttributedString(string:"5\n",attributes:[NSAttributedString.Key.font:UIFont.boldSystemFont(ofSize: 14)])

        attributedText.append(NSAttributedString(string:"posts",attributes: [NSAttributedString.Key.font:UIFont.boldSystemFont(ofSize: 14), NSAttributedString.Key.foregroundColor:UIColor.lightGray]))
        label.attributedText = attributedText
        return label
    }()

    let followersLabel: UILabel = {
         let label = UILabel()
          label.numberOfLines = 0
          label.textAlignment = .center



          return label
      }()
    let followingLabel: UILabel = {
           let label = UILabel()
            label.numberOfLines = 0
            label.textAlignment = .center
        let attributedText = NSMutableAttributedString(string:"5\n",attributes:[NSAttributedString.Key.font:UIFont.boldSystemFont(ofSize: 14)])
        attributedText.append(NSAttributedString(string:"following",attributes:[NSAttributedString.Key.font:UIFont.boldSystemFont(ofSize: 14), NSAttributedString.Key.foregroundColor:UIColor.lightGray]))
                    label.attributedText = attributedText

            return label
        }()

    let editProfileFollowButton : UIButton = {
        let button  = UIButton(type: .system)
        button.setTitle("Loading", for: .normal)
        button.layer.cornerRadius = 5
        button.layer.borderColor = UIColor.lightGray.cgColor
        button.layer.borderWidth = 0.5
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
        button.setTitleColor(.black, for: .normal)
        button.addTarget(self, action: #selector(handleEditProfileFollow), for: .touchUpOutside)


        return button
    }()

    let gridButton : UIButton = {
        let button = UIButton(type: .system)
        button.setImage(UIImage(named: "grid"), for: .normal)
        return button
    }()

    let listButton : UIButton = {

        let button = UIButton(type: .system)
        button.setImage(UIImage(named:"list"), for: .normal)
        button.tintColor = UIColor(white: 0, alpha: 0.2)
        return button
    }()
    let  bookmarkButton : UIButton = {

          let button = UIButton(type: .system)
          button.setImage(UIImage(named:"ribbon"), for: .normal)
          button.tintColor = UIColor(white: 0, alpha: 0.2)
        button.addTarget(self, action: #selector(testFunc(_:)), for: UIControl.Event.touchUpInside)
          return button
      }()



    @objc func testFunc(_ sender : UIButton){
        print("Pressed ")
    }

    @objc func handleFollowersTapped() {
        delegate?.handleFollowersTapped(for: self)
    }

    @objc func handleFollowingTapped() {
        delegate?.handleFollowingTapped(for: self)
    }

    @objc func handleEditProfileFollow() {

        guard let user = self.user else {return}

        if editProfileFollowButton.titleLabel?.text == "Edit Profile"{
            print("Handler edit profile ")
       }
        else{
            if editProfileFollowButton.titleLabel?.text == "Follow"{
                editProfileFollowButton.setTitle("Following", for: .normal)
                user.follow()
            }else{
                editProfileFollowButton.setTitle("Follow", for: .normal)
                user.unfollow()


            }
        }

    }

Try this, i think this will help you.

 class customCell: UICollectionViewCell {
    @IBOutlet weak var btn: UIButton!

    override func awakeFromNib() {
        super.awakeFromNib()
    }
  }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

           let cell: customCell = collectionView.dequeueReusableCell(withReuseIdentifier: "customCell", for: indexPath) as! customCell

            cell.btn.tag = indexPath.row
            cell.btn.addTarget(self, action: #selector(self.btnpressed(sender:)), for: .touchUpInside)
             return cell
     }
     @objc func btnpressed(sender: UIButton!)  {
           print(sender.tag)

      }

override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

    let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: customCell, for: indexPath) as! customCell

    view.pagePluginButtonAction = {
        self.TapedBtn()
    }

    return view
}
func TapedBtn(){

    print("click")
}

You need to add the target in 'viewForSupplementaryElementOfKind' where you set up your header. See example below, just after you set the header delegate.

    override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

               // Declare header
            let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerIdentifier, for: indexPath) as! UserProfileHeader

            // set delegate
            header.delegate = self

// Add the target here 
header.yourButton.addTarget(self, action: #selector(handleYourButton), for: .touchUpInside)


if let user = self.currentUser {
                header.user = user
            } else if let userToLoadFromSearchVC = self.userToLoadFromSearchVC {
                header.user = userToLoadFromSearchVC
                self.navigationItem.title = userToLoadFromSearchVC.username

            }
            // Return header

               return header
           }

This is because you are creating the button target before the UserProfileHeader initialized. So you need to create the button using lazy var (lazily).

private lazy var button: UIButton = {
    let button = UIButton()
    button.setTitle("Button", for: .normal)
    button.addTarget(self, action: #selector(handleButtonTapped), for: .touchUpInside)
    return button
}()

@objc private func handleButtonTapped() {
    print("Button tapped")
}

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