質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

Q&A

解決済

2回答

1275閲覧

FIrebaseでフォロー・アンフォローを実装したい

amazon_106

総合スコア50

Swift

Swiftは、アップルのiOSおよびOS Xのためのプログラミング言語で、Objective-CやObjective-C++と共存することが意図されています

0グッド

0クリップ

投稿2019/02/19 07:19

編集2019/02/19 14:32

##現在詰まっているところ
followボタンをクリックしprint("タップ")を出力したい

######ボタンを設置しているファイル

UserProfileHeader.swift import UIKit import Firebase class UserProfileHeader: UICollectionViewCell { // MARK: - Properties var delegate: UserProfileHeaderDelegate? var user: User? { didSet { // configure edit profile button configureEditProfileFollowButton() // set user stats setUserStats(for: user) let fullName = user?.name nameLabel.text = fullName profileImageView.loadImage(with: (user?.profileImageUrl)!) } } let profileImageView: UIImageView = { let iv = UIImageView() iv.contentMode = .scaleAspectFill iv.clipsToBounds = true iv.backgroundColor = .red return iv }() let nameLabel: UILabel = { let label = UILabel() label.font = UIFont.boldSystemFont(ofSize: 12) return label }() let editProfileFollowButton: UIButton = { let button = UIButton(type: .system) button.layer.cornerRadius = 3 button.layer.borderColor = UIColor.lightGray.cgColor button.addTarget(self, action: #selector(handleEditProfileFollow), for: .touchUpInside) button.layer.borderWidth = 0.5 button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14) button.setTitleColor(.black, for: .normal) return button }() // MARK: - Handlers @objc func handleEditProfileFollow() { delegate?.handleEditFollowTapped(for: self) } func setUserStats(for user: User?) { guard let uid = user?.uid else { return } var numberOfFollowers: Int! var numberOfFollowing: Int! // get number of followers USER_FOLLOWER_REF.child(uid).observeSingleEvent(of: .value) { (snapshot) in if let snapshot = snapshot.value as? Dictionary<String, AnyObject> { numberOfFollowers = snapshot.count } else { numberOfFollowers = 0 } let attributedText = NSMutableAttributedString(string: "(numberOfFollowers!) \n", attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 14)]) attributedText.append(NSAttributedString(string: "followers", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: UIColor.lightGray])) self.followersLabel.attributedText = attributedText } // get number of following USER_FOLLOWING_REF.child(uid).observeSingleEvent(of: .value) { (snapshot) in if let snapshot = snapshot.value as? Dictionary<String, AnyObject> { numberOfFollowing = snapshot.count } else { numberOfFollowing = 0 } let attributedText = NSMutableAttributedString(string: "(numberOfFollowing!) \n", attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 14)]) attributedText.append(NSAttributedString(string: "following", attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: UIColor.lightGray])) self.followingLabel.attributedText = attributedText } } func configureEditProfileFollowButton(){ guard let currentUid = Auth.auth().currentUser?.uid else { return } guard let user = self.user else { return } if currentUid == user.uid { // configure button as edit profile editProfileFollowButton.setTitle("テストプロフィールを編集", for: .normal) } else { // configure button as follow button editProfileFollowButton.setTitleColor(.white, for: .normal) editProfileFollowButton.backgroundColor = UIColor(red: 17/255, green: 154/255, blue: 237/255, alpha: 1) user.checkIfUserIsFollowed (completion: { (followed) in if followed { self.editProfileFollowButton.setTitle("following", for: .normal) } else { self.editProfileFollowButton.setTitle("follow", for: .normal) } }) } } // MARK: - Init override init(frame: CGRect) { super.init(frame: frame) addSubview(profileImageView) profileImageView.anchor(top: self.topAnchor, left: self.leftAnchor, bottom: nil, right: nil, paddingTop: 16, paddingLeft: 12, paddingBottom: 0, paddingRight: 0, width: 80, height: 80) profileImageView.layer.cornerRadius = 80 / 2 addSubview(nameLabel) nameLabel.anchor(top: profileImageView.bottomAnchor, left: self.leftAnchor, bottom: nil, right: nil, paddingTop: 12, paddingLeft: 12, paddingBottom: 0, paddingRight: 0, width: 0, height: 0) configureUserStats() addSubview(editProfileFollowButton) editProfileFollowButton.anchor(top: postsLabel.bottomAnchor, left: postsLabel.leftAnchor, bottom: nil, right: self.rightAnchor, paddingTop: 4, paddingLeft: 8, paddingBottom: 0, paddingRight: 12, width: 0, height: 30) configureBottomToolBar() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
後にUserProfile.swiftでフォロー・アンフォローを実装したいので、Protocolsファイルに設定
Protocols.swift protocol UserProfileHeaderDelegate { func handleEditFollowTapped(for header: UserProfileHeader) }
print("タップ")を実装したファイル
UserProfile.swift import UIKit import Firebase private let reuseIdentifier = "Cell" private let headerIdentifier = "UserProfileHeader" class UserProfileVC: UICollectionViewController, UICollectionViewDelegateFlowLayout, UserProfileHeaderDelegate { // MARK: - Properties var currentUser: User? var userToLoadFromSearchVC: User? override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Register cell classes self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) self.collectionView!.register(UserProfileHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: headerIdentifier) self.collectionView.backgroundColor = .white if userToLoadFromSearchVC == nil { fetchCurrentUserData() } } // MARK: - UICollectionView 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 } 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 { // UserProfileHeader のuser header.user = user } else if let userToLoadFromSearchVC = self.userToLoadFromSearchVC { header.user = userToLoadFromSearchVC navigationItem.title = userToLoadFromSearchVC.username } // return header return 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, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) // Configure the cell return cell } // MARK: - UserProfileHeader Protocol func handleEditFollowTapped(for header: UserProfileHeader) { print("タップ") } // MARK: - API func fetchCurrentUserData() { // set the user in header guard let currentUid = Auth.auth().currentUser?.uid else { return } Database.database().reference().child("users").child(currentUid).observeSingleEvent(of: .value) { (snapshot) in guard let dictionary = snapshot.value as? Dictionary<String, AnyObject> else { return } let uid = snapshot.key let user = User(uid: uid, dictionary: dictionary) self.currentUser = user self.navigationItem.title = user.username self.collectionView.reloadData()     }   } }

イメージ説明

この状態でfollowボタンを押しても、Thread 1: breakpoint 2.1もコンソール上にも反応がありませんでした。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

fuzzball

2019/02/19 07:38

コードを変に省略しないで下さい。
guest

回答2

0

自己解決

UserProfileHeaderの

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

の変数を
これを参考に

lazy var

にしたら無事出力出来ました。

投稿2019/02/19 16:34

amazon_106

総合スコア50

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

takabosoft

2019/02/20 00:30

ああ、なるほど、これってlazyが無いとselfを使っている時点でコンパイルエラーが出ていませんでしたか?
amazon_106

2019/02/20 12:43

返信遅くなりました。 出てなかったと思います。
amazon_106

2019/02/20 12:58

UserProfileVC(実装の為のファイル)では出ました。 ``` // MARK: - UserProfileHeader Protocol func handleEditFollowTapped(for header: UserProfileHeader) { guard let user = header.user else { return } if editProfileFollowButton.titleLabel?.text == "Edit Profile" ``` エラーメッセージはUse of unresolved identifier 'editProfileFollowButton'で header.editProfileFollowButton.titleLabel?.textとすることでエラーは消えました。
guest

0

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

のforのあとを.touchUpInsideにしてください。
(あれ変わってた?)

@objc func handleEditProfileFollow() {

@objc func handleEditProfileFollow(_ sender: UIButton) {の方が良いかもしれません。

投稿2019/02/19 08:09

編集2019/02/19 08:15
takabosoft

総合スコア8356

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

amazon_106

2019/02/19 08:20

回答ありがとうございます。 やってみましたが、状況変らずでした。
fuzzball

2019/02/19 08:22

handleEditProfileFollow()が呼ばれているかどうか聞いたほうが早いのでは?
takabosoft

2019/02/19 08:26

ですね。handleEditProfileFollowは呼ばれてますか?
takabosoft

2019/02/19 08:27

あとはブレークポイント貼ってステップインなりすればすぐに判るかと。
amazon_106

2019/02/19 14:14

すいません、handleEditProfileFollow()が呼ばれているかどうか、どうやって確かめればよいでしょうか。 ググってみたんですが、検索ワードが悪いらしく有用そうなものが出てきませんでした。 やり方を教えていただけないでしょうか。
amazon_106

2019/02/19 14:16

ブレークポイントからステップインは、いろんな情報が出てきたのでそれを元にやってみます。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問