Jestem nowicjuszem, mam następujący problem. Jest taki ekran jak na tym obrazku. Używam UICollectionViewCell jako nagłówka i nie mogę addTarget dla niebieskiego przycisku w tym.

enter image description here

Nie dam rady. Czy mógłbyś mi pomóc?

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) {

    }

To jest mój kod w pliku nagłówkowym.

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()


            }
        }

    }
1
Phạm Hùng 2 kwiecień 2020, 15:02

3 odpowiedzi

Najlepsza odpowiedź

Dzieje się tak, ponieważ tworzysz cel przycisku przed zainicjalizowaniem UserProfileHeader. Musisz więc utworzyć przycisk za pomocą lazy var (leniwie).

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")
}
0
Frankenstein 2 kwiecień 2020, 14:36

Spróbuj tego, myślę, że to ci pomoże.

 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")
}
0
Vandana pansuria 2 kwiecień 2020, 12:49

Musisz dodać cel w „viewForSupplementaryElementOfKind”, gdzie konfigurujesz swój nagłówek. Zobacz przykład poniżej, zaraz po ustawieniu delegata nagłówka.

    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
           }
0
James.dev 2 kwiecień 2020, 14:36