2016-09-26 6 views
1

私は頭を包むことができないという問題があります。あなたはUITableViewControllerでボタンアクションを作成できません。ボタンからdetailtableViewControllerしかし、私はprepareForSegueを使用し、ボタンをクリックするとdetailtableViewControllerの文字列にボタンのテキストを送信するはずですが、tableViewに複数のセルがあり名前が正しいため、正しい名前ではないことがあります常にではない、私はそれを行うために必要なものと同じ..Button from UITableViewController detailViewControllerにデータを送信します - swift

は、あなたがボタン「ボタンをクリックすると、次のとおりです。 enter image description here

このdetailtableViewControllerに移動する必要があります。 enter image description here

ボタンにテキストとして設定されている名前です。 ボタンの名前を受け取る変数は、viaSegueと呼ばれ、文字列です。

私のUITableViewController:

class feedTableViewController: UITableViewController, PostCellDelegate { 



     @IBOutlet weak var loadingSpinner: UIActivityIndicatorView! 
     @IBOutlet weak var profilePicture: UIImageView! 


     var sendName = "No name" 
     var facebookProfileUrl = "" 
     var dbRef: FIRDatabaseReference! 
     var updates = [Sweet]() 
     var gottenUserId : Bool? = false 
     var gottenUserIdWorkout : Bool? = false 

     override func viewDidLoad() { 
      super.viewDidLoad() 

      let logoImage = UIImageView(frame: CGRect(x:0, y:0, width: 60, height: 32)) 
      logoImage.contentMode = .ScaleAspectFit 

      let logo = UIImage(named: "logo.png") 
      logoImage.image = logo 
      self.navigationItem.titleView = logoImage 



      loadingSpinner.startAnimating() 


      if let user = FIRAuth.auth()?.currentUser { 

       let userId = user.uid 


       let storage = FIRStorage.storage() 

       // Refer to your own Firebase storage 
       let storageRef = storage.referenceForURL("**********") 

       let profilePicRef = storageRef.child(userId+"/profile_pic.jpg") 

       // Download in memory with a maximum allowed size of 1MB (1 * 1024 * 1024 bytes) 
       profilePicRef.dataWithMaxSize(1 * 300 * 300) { (data, error) -> Void in 
        if (error != nil) { 
         // Uh-oh, an error occurred! 
         print("Unable to download image") 
        } else { 
         // Data for "images/island.jpg" is returned 
         // ... let islandImage: UIImage! = UIImage(data: data!) 
         if (data != nil){ 
          self.profilePicture.image = UIImage(data: data!) 
          self.profilePicture.layer.cornerRadius = self.profilePicture.frame.size.width/2 
          self.profilePicture.clipsToBounds = true 

         } 
        } 
       } 


      } 

      dbRef = FIRDatabase.database().reference().child("feed-items") 
      startObersvingDB() 

      tableView.rowHeight = UITableViewAutomaticDimension 
      tableView.estimatedRowHeight = 205 
     } 

     func startObersvingDB() { 
      FIRDatabase.database().reference().child("feed-items").queryOrderedByChild("date").observeEventType(.Value, withBlock: { (snapshot: FIRDataSnapshot) in 
       var newUpdates = [Sweet]() 

       for update in snapshot.children { 
        let updateObject = Sweet(snapshot: update as! FIRDataSnapshot) 
        newUpdates.append(updateObject) 

       } 

       self.updates = newUpdates.reverse() 
       self.tableView.reloadData() 


      }) { (error: NSError) in 
       print(error.description) 
      } 
     } 





     override func didReceiveMemoryWarning() { 
      super.didReceiveMemoryWarning() 

     } 












     // MARK: - Table view data source 

     override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
      return 1 
     } 

     override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
      return updates.count 
     } 


     protocol PostCellDelegate: class { 
      func postCell(postCell: PostCell, didTouchUpInside button: UIButton) 
     } 


     func postCell(postCell: PostCell, didTouchUpInside button: UIButton) { 
      let identifier = "toDetailtableViewController" 
      let username = postCell.nameButton.titleLabel?.text 
      performSegue(withIdentifier: identifier, sender: username) 
     } 






     override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

// Lots of stuff happening here 

マイカスタムセル:

class updateTableViewCell: UITableViewCell { 

    @IBOutlet weak var updateLabel: UILabel! 
    @IBOutlet weak var picView: UIImageView! 
    @IBOutlet weak var likesLabel: UILabel! 
    @IBOutlet weak var likeButton: UIButton! 
    @IBOutlet weak var hand: UIImageView! 
    @IBOutlet weak var dateLabel: UILabel! 

    @IBOutlet weak var nameButton: UIButton! 


    weak var delegate: PostCellDelegate? 

    var pathDB : String! 
    var dbRef: FIRDatabaseReference! 
    var gottenUserId : Bool? = false 
    var sendNameCell = "No name here" 




    override func awakeFromNib() { 
     super.awakeFromNib() 
     // Initialization code 

    } 

    override func setSelected(selected: Bool, animated: Bool) { 
     super.setSelected(selected, animated: animated) 

     // Configure the view for the selected state 
    } 

    @IBAction func likeTapped(sender: AnyObject) { 
     //print(pathDB) 
     checkClickOnLikeButton() 


    } 


    @IBAction func didTouchUpInsideButton(sender: AnyObject) { 
     delegate?.postCell(self, didTouchUpInside: button) 
    } 




    func checkClickOnLikeButton() { 
     let dataPathen = self.pathDB 
     // print(dataPathen) 


     if let user = FIRAuth.auth()?.currentUser { 

      let userId = user.uid 



      FIRDatabase.database().reference().child("feed-items").child(dataPathen).child("likesForPost").observeSingleEventOfType(.Value, withBlock: { (snapshot) in 
       // Get user value 
       self.gottenUserId = snapshot.value![userId] as? Bool 

       // print(self.gottenUserId) 

       if self.gottenUserId == true { 
        print("Der er trykket high five før") 
        FIRDatabase.database().reference().child("feed-items").child(dataPathen).child("likesForPost").child(userId).removeValue() 
        let greyButtonColor = UIColor(red: 85/255, green: 85/255, blue: 85/255, alpha: 1.0) 
        self.likeButton.setTitleColor(greyButtonColor, forState: UIControlState.Normal) 
        self.hand.image = UIImage(named: "high.png") 
       } else { 
        print("Der er IKKE trykket like før") 
        let quoteString = [userId: true] 
        FIRDatabase.database().reference().child("feed-items").child(dataPathen).child("likesForPost").updateChildValues(quoteString) 
        let blueButtonColor = UIColor(red: 231/255, green: 45/255, blue: 60/255, alpha: 1.0) 
        self.likeButton.setTitleColor(blueButtonColor, forState: UIControlState.Normal) 
        self.hand.image = UIImage(named: "highfive.png") 
       } 


       // ... 
      }) { (error) in 
       print(error.localizedDescription) 
      } 



     } 

    } 









} 
+0

あなたの 'prepareforsegue'メソッドを問題に追加し、ボタンのクリックで' performsegue'を呼び出していますか? – Lion

+0

私はprepareforsegueを追加しました..いいえ、私はカスタムセルクラスを持っているので、送信する必要があるデータが自分のUITableViewControllerにあるときにそのクラスからデータを取得できません。私はカスタムセルでパフォーマンスを使用することはできませんか? –

答えて

0

すでにButtonを含むセル用のカスタムクラスを作成していると仮定すると、あなたはdidTouchUpInsideイベントの@IBActionを作成する必要があります。また、UITableViewControllerからdetailtableViewControllerまでのセグを直接作成する必要があります(ボタンまたはビューではなく、ビューコントローラからビューコントローラへ)。手動で実行するので、このセグの識別子を与える必要があります。

セルに@IBActionを接続したら、セルからセグを実行する方法が必要です。これを行うには、UITableViewControllerへの参照が必要です。私は代理人や多分レスポンダを使ってそれを得ることができました、最近私はレスポンダを使っています。

委任

あなたUITableViewControllerが準拠するためのプロトコルを作成します。

protocol PostCellDelegate: class { 
    func postCell(_ postCell: PostCell, didTouchUpInside button: UIButton) 
} 

それは、ボタンの@IBActionそのイベントのからdidTouchUpInside方法だカスタムセルクラスの呼び出しでデリゲート変数を作成します。あなたのUITableViewControllerで今

weak var delegate: PostCellDelegate? 

@IBAction func didTouchUpInsideButton() { 
    delegate?.postCell(self, didTouchUpInside: button) 
} 

、あなたはデリゲートに準拠し、cellForRowAt方法では細胞のデリゲートを設定する必要があります。

class tableViewController: UITableViewController, PostCellDelegate { 

    //... 

    // MARK: PostCellDelegate 

    func postCell(_ postCell: PostCell, didTouchUpInside button: UIButton) { 
     let identifier = "toDetailtableViewController" 
     let username = postCell.button.titleLabel?.text 
     performSegue(withIdentifier: identifier, sender: username) 
    } 

    //... 

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     ... 
     cell.delegate = self 
     return cell 
    } 

    //... 

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 

     super.prepare(for: segue, sender: sender) 

     switch (segue.destination, sender) { 
     case let (controller as detailtableViewController, username as String): 
      controller.usernameTextField.text = username 
      break 
     default: 
      break 
     } 
    } 
} 
+0

あなたの時間をありがとうCallam!私はあなたのコードを使用し、いくつかのエラーが発生しました..私はあなたの投稿に続いたので、ここで何が間違っているかも知っていますか?あなたの答えが私のエラーの場所で更新されました:-) –

+0

カスタムセルクラスの名前が – Callam

+0

だったと言っていないので、ポストセルクラスの名前を変更する必要があります。コード、私は助けることができます – Callam

関連する問題