【问题标题】:Passing data from UITableview using Protocol in Swift and Firebase在 Swift 和 Firebase 中使用协议从 UITableview 传递数据
【发布时间】:2017-10-28 19:24:07
【问题描述】:

我有一个名为 PostsTableView 的 tableview,它有一个用户帖子列表,其中包含一个名为“Comment”的 UIButton。当用户单击 Comment 时,我希望它重定向到 CommentViewController,其中包含帖子周围的所有信息,例如 postText 和撰写帖子的用户。

下面的代码片段。

PostsTableView

extension PostsTableViewController: PostsTableViewCellDelegate {

  func commentTapped(postInfo: String) {

  //How do I pass postInfo along to CommentViewController

  }

PostsTableViewCell

protocol TableViewCellDelegate {

  func commentTapped(postInfo: String)

}

class PostsTableViewCell: UITableViewCell {

@IBOutlet weak var postTextLabel: UILabel!
@IBOutlet weak var postUserLabel: UILabel!

var postItem: Post!
var delegate: TableViewCellDelegate?

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

@IBAction func commentAction(_ sender: Any) {

delegate?.commentTapped(postInfo: postItem.postText)

}
}

【问题讨论】:

    标签: swift firebase swift3 firebase-realtime-database


    【解决方案1】:

    假设您正在使用 segues,您将调用 .performSegue(withIdentifier: "mySegueIdentifier", sender: self)

    您可以首先通过向PostsTableViewController 添加一个变量来存储postInfo

    var selectedPostInfo: String?
    

    然后设置在commentTapped(postInfo: String)

    func commentTapped(postInfo: String) {
        selectedPostInfo = postInfo
    
        performSegue(withIdentifier: "mySegueIdentifier")
    }
    

    现在覆盖controller.prepare(for: UIStoryboardSegue, sender: Any?) 并设置CommentViewController 的值:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let controller = segue.destination as? CommentViewController {
            controller.postInfo = selectedPostInfo
        }
    }
    

    【讨论】:

      【解决方案2】:

      你可以这样做

      1) 首先重构委托方法以将 post 对象作为参数,而不仅仅是一个字符串(这有助于提供更好的用户体验,因为此时无需获取本地已经可用的数据)。像这样的

      func commentTapped(postObject: Post) { // I am assuming your Post model has got all the info required by the CommentsViewController
        }
      

      2) 现在在 CommentsViewController 中创建一个属性,比如说 post,你可以按照下面的代码初始化它

      func commentTapped(postObject: Post) {
       let commentVC = CommentsViewController.initWithNib... // Initialise the Comments ViewController
       commentVC.post = postObject // Assign the post object here
       show(commentVC) // Present here the commentVC as per your requirement of Modal or Push
      }
      

      【讨论】:

        猜你喜欢
        • 2021-06-21
        • 2015-03-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多