使用单击的按钮通过tableView传递数据

时间:2018-06-09 22:14:56

标签: ios swift uitableview

我有一个按钮,即用户名。当我点击用户名时,我想传递数据,我也想获取所选用户名的用户ID。我知道它不起作用,因为我知道我在技术上没有选择一行。关于如何获取按钮的行索引的任何提示,谢谢。

这是我的ViewController

import UIKit
import Firebase
import FirebaseAuth
import FirebaseStorage
import FirebaseDatabase

class DiscussionListTableViewController: UITableViewController, PostCellDelegate {
    var postRef: DatabaseReference!
    var storageRef: StorageReference!
    var posts = [Posts]()

    @IBAction func profileAction(_ sender: Any) {
       if Auth.auth().currentUser == nil {
            performSegue(withIdentifier: "toLogin", sender: self)
            print("no user logged in")
        } else {
            performSegue(withIdentifier: "toProfile", sender: self)
        }
    }

    override func viewDidAppear(_ animated: Bool) {
        postRef = Database.database().reference().child("posts")
        postRef.observe(DataEventType.value, with: { (snapshot) in
            var newPosts = [Posts]()

            for post in snapshot.children {
                let post = Posts(snapshot: post as! DataSnapshot)
                newPosts.insert(post, at: 0)
            }
            self.posts = newPosts
            self.tableView.reloadData()
        }, withCancel: {(error) in
            print(error.localizedDescription)
        })
    }

    override func viewDidLoad() {
        tableView.rowHeight = 160
        super.viewDidLoad()
    }

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

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "postCell", for: indexPath) as! PostTableViewCell
        cell.usernameLabel.setTitle(posts[indexPath.row].username, for: .normal)
        cell.postDescriptionLabel.text = posts[indexPath.row].description
        cell.postTitleLabel.text = posts[indexPath.row].title
        let image = posts[indexPath.row]
        cell.userProfilePic.sd_setImage(with: URL(string: image.userImageStringUrl), placeholderImage: UIImage(named: "1"))
        cell.postImageView.sd_setImage(with: URL(string: image.postImageStringUrl), placeholderImage: UIImage(named: "1"))

        cell.delegate = self

        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        performSegue(withIdentifier: "addComment", sender: self)
    }

    func usernameClicked() {
        performSegue(withIdentifier: "viewProfile", sender: self)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "addComment" {
            let commentVC = segue.destination as! CommentTableViewController
            let indexPath = tableView.indexPathForSelectedRow!
            let selectedIndex = posts[indexPath.row]
            commentVC.selectedPost = posts[indexPath.row]
            commentVC.postDescription = selectedIndex.description
            commentVC.postImageUrl = selectedIndex.postImageStringUrl
            commentVC.postTitle = selectedIndex.title
            commentVC.postUsername = selectedIndex.username
            commentVC.profilePicUrl = selectedIndex.userImageStringUrl
        } else {
            if segue.identifier == "viewProfile" {
                let viewProfileVC = segue.destination as? ViewProfileViewController
                let indexPath = tableView.indexPathForSelectedRow
                let selectedIndex = posts[indexPath.row]
                viewProfileVC?.username = selectedIndex.username
                viewProfileVC?.userid = selectedIndex.userid
            }
        }
    }
}

猜测我的错误就在这里,因为当我点击按钮时我实际上并没有选择一行:

 if segue.identifier == "viewProfile" {
    let viewProfileVC = segue.destination as?     ViewProfileViewController
    let indexPath = tableView.indexPathForSelectedRow
    let selectedIndex = posts[indexPath.row]
    viewProfileVC?.username = selectedIndex.username
    viewProfileVC?.userid = selectedIndex.userid
}

这是我的TableViewCell

import UIKit
import Foundation

protocol PostCellDelegate {
    func usernameClicked()
}

class PostTableViewCell: UITableViewCell {
    var delegate: PostCellDelegate?

    @IBOutlet weak var userProfilePic: UIImageView!

    @IBOutlet weak var usernameLabel: UIButton!
    @IBOutlet weak var postImageView: UIImageView!
    @IBOutlet weak var postDescriptionLabel: UILabel!
    @IBOutlet weak var postTitleLabel: UILabel!

    @IBAction func usernameButtonAction(_ sender: Any) {
        print("Username clicked")
        self.delegate?.usernameClicked()
    }

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

以下是我正在尝试将数据传递给的视图控制器。

import UIKit
import Firebase
import FirebaseDatabase
import FirebaseStorage
import FirebaseAuth

class ViewProfileViewController: UIViewController {
    var clickedUserRef: DatabaseReference!
    var userid = ""
    var username = ""
}

1 个答案:

答案 0 :(得分:3)

您需要将单元格作为参数传递给usernameClicked委托方法。

然后表视图控制器可以询问表视图单元的索引路径是什么。然后从索引路径中获取所需的数据。

更新协议:

protocol PostCellDelegate {
    func usernameClicked(_ cell: PostTableViewCell)
}

更新按钮处理程序:

@IBAction func usernameButtonAction(_ sender: Any) {
    print("Username clicked")
    self.delegate?.usernameClicked(self)
}

向`DiscussionListTableViewController:

添加一个属性
var clickedPath: IndexPath? = nil

更新视图控制器中的方法:

func usernameClicked(_ cell: PostTableViewCell) {
    if let indexPath = self.tableView.indexPath(for: cell) {
        clickedPath = indexPath
        performSegue(withIdentifier: "viewProfile", sender: self)
    }
}

然后在prepare(for:)中,替换使用:

let indexPath = tableView.indexPathForSelectedRow!

使用:

if let indexPath = clickedPath {
    // get the row
    // access the posts data
}
相关问题