UIButton в заголовке представления коллекции не работает при вызове из контроллера представления коллекции, как это исправить? - PullRequest
1 голос
/ 09 июля 2019

У меня есть файл UICollectionViewCell, состоящий из кнопки.Когда я нажимаю эту кнопку, я хочу изменить метку кнопки с «follow» на «unfollow» (например, instagram), и я вызываю эту функцию по нажатию кнопки в моем swift-файле контроллера UICollectionView, используя протоколы и делегаты.Но кнопка просто не реагирует.

Я добавил UICollectionViewCell в качестве дополнительного ViewofKind также в контроллере, и все же есть проблема.Также удостоверился, что я соответствовал протоколу делегата

// ********* VIEW FILE (UserProfileHeader.swift) *********
class UserProfileHeader: UICollectionViewCell {

var delegate: UserProfileHeaderDelegate?

let editProfileFollowButton: UIButton = {
 let button = UIButton(type: .system)
 button.setTitle("Follow", for: .normal)
 button.addTarget(self, action: #selector(handleEditProfileFollow), 
 for: .touchUpInside)
 return button
    }()

override init(frame: CGRect) {
  super.init(frame: frame)

  addSubview(editProfileFollowButton)

    }

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

}

// ********* CONTROLLER FILE (UserProfileVC.swift) *********
class UserProfileVC: UICollectionViewController, 
UICollectionViewDelegateFlowLayout, UserProfileHeaderDelegate {

override func viewDidLoad() {
    super.viewDidLoad()

    //register collection views
    self.collectionView!.register(UICollectionViewCell.self, 
    forCellWithReuseIdentifier: reuseIdentifier)

    self.collectionView.register(UserProfileHeader.self, 
    forSupplementaryViewOfKind: 
    UICollectionView.elementKindSectionHeader, withReuseIdentifier: 
    headerIdentifier)

}


override func numberOfSections(in collectionView: UICollectionView) 
-> Int {
    return 1
}


override func collectionView(_ collectionView: UICollectionView, 
numberOfItemsInSection section: Int) -> Int {
    return 0
}

// declaring the header collection view
override func collectionView(_ collectionView: UICollectionView, 
viewForSupplementaryElementOfKind kind: String, at indexPath: 
IndexPath) -> UICollectionReusableView {
    let header = 
      collectionView.dequeueReusableSupplementaryView(ofKind: kind, 
      withReuseIdentifier: headerIdentifier, for: indexPath) as! 
      UserProfileHeader
    header.delegate = self
    return header
}

func collectionView(_ collectionView: UICollectionView, layout 
collectionViewLayout: UICollectionViewLayout, 
referenceSizeForHeaderInSection section: Int) -> CGSize {
    return CGSize(width: view.frame.width, height: 220)
}

override func collectionView(_ collectionView: UICollectionView, 
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = 
      collectionView.dequeueReusableCell(withReuseIdentifier: 
      reuseIdentifier, for: indexPath)
    return cell
}


func handleEditFollowTapped(for header: UserProfileHeader){
    if header.editProfileFollowButton.titleLabel?.text == "Follow"{
        header.editProfileFollowButton.setTitle("Following", for: 
          .normal)
    } else {
        header.editProfileFollowButton.setTitle("Follow", for: 
          .normal)
    }
}

}

// ********* PROTOCOL FILE (protocols.swift) *********
protocol UserProfileHeaderDelegate {
 func handleEditFollowTapped(for header: UserProfileHeader)
}

1 Ответ

0 голосов
/ 09 июля 2019

Проблема, которую я вижу, состоит в том, что вы не можете добавить цель в anonymous closure, причина в том, что self не существует в момент создания кнопки.

И легко исправить это может быть удаление строки, следующей за строкой при создании кнопок:

button.addTarget(self, action: #selector(handleEditProfileFollow), for: .touchUpInside)

А в init просто добавьте следующую строку после super.init:

editProfileFollowButton.addTarget(self, action: #selector(handleEditProfileFollow), for: .touchUpInside)

Надеюсь, это поможет 101

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...