我目前正在 Xcode 14.2 上开发社交媒体应用程序。在这一点上,我要集成一个功能评论系统,用户可以在其中查看帖子的现有评论并留下自己的评论。我已经让它有点工作了,因为一个问题困扰着我。
目前的工作原理是,在每个帖子下都会有一个文本符号,作为一个按钮。当用户按下按钮时,他们将被重定向到评论部分,在那里他们可以查看其他用户的评论,也可以通过点击创建评论按钮来发表自己的评论。问题在于,当用户发表评论时,评论会显示在应用程序中所有现有帖子的下方,而不仅仅是用户选择评论的帖子。我如何确保每个帖子都有自己独特的评论部分,以便当用户发表评论时它只显示在该帖子上,而不是让评论显示在所有帖子上?
这里是涉及到的代码:
CommentViewController
import UIKit
import Parse
class CommentViewController: UIViewController, UITableViewDataSource, UITableViewDelegate
{
var selectedPost: PFObject!
var comments: [PFObject] = []
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
loadComments()
}
func loadComments()
{
let query = PFQuery(className: "Comment")
query.whereKey("post", equalTo: selectedPost)
query.includeKey("author")
query.findObjectsInBackground
{
[weak self] comments, error in
if let comments = comments
{
self?.comments = comments
self?.tableView.reloadData()
} else if let error = error
{
print("Error loading comments: \(error.localizedDescription)")
}
}
}
@IBAction func onCreateComment(_ sender: Any)
{
let alertController = UIAlertController(title: "Add Comment", message: nil, preferredStyle: .alert)
alertController.addTextField
{
textField in
textField.placeholder = "Enter your comment here"
}
let postAction = UIAlertAction(title: "Post", style: .default)
{
[weak self] _ in
guard let commenttext = alertController.textFields?.first?.text
else
{
return
}
let newComment = PFObject(className: "Comment")
newComment["author"] = PFUser.current() ?? NSNull()
newComment["text"] = commenttext
newComment["post"] = self?.selectedPost ?? NSNull()
newComment.saveInBackground
{
[weak self] success, error in
if success
{
self?.loadComments()
}
else if let error = error
{
print("Error saving comment: \(error.localizedDescription)")
}
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(postAction)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return comments.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "CommentCell", for: indexPath) as! CommentCell
let comment = comments[indexPath.row]
cell.commentTextLabel.text = comment["text"] as? String
if let user = comment["author"] as? PFUser
{
cell.nameLabel.text = user.username
}
else
{
cell.nameLabel.text = "Unknown"
}
return cell
}
}
CommentCell
import UIKit
class CommentCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var commentTextLabel: UILabel!
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
}
}
任何和所有反馈/建议将不胜感激!
更新:我已经将
selectedPost
更改为postObject
。 CommentViewController 在创建实例方面的工作方式是 FeedViewController
中有一个按钮连接到它,按下时会以模态方式显示。下面是我的CommentViewController
现在的样子
import UIKit
import Parse
class CommentViewController: UIViewController, UITableViewDataSource, UITableViewDelegate
{
var postObject: PFObject!
var comments: [PFObject] = []
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
if postObject != nil
{
loadComments()
}
}
func loadComments()
{
guard let postObject = postObject else
{
print("Error: postObject is nil")
return
}
guard let postId = postObject.objectId else
{
print("Error: postId is nil")
return
}
let postQuery = PFQuery(className: "Posts")
postQuery.whereKey("objectId", equalTo: postId)
let query = PFQuery(className: "Comment")
query.whereKey("post", equalTo: postObject)
query.whereKey("post", matchesQuery: postQuery)
query.includeKey("author")
query.findObjectsInBackground
{
[weak self] comments, error in
if let comments = comments
{
self?.comments = comments
self?.tableView.reloadData()
} else if let error = error
{
print("Error loading comments: \(error.localizedDescription)")
}
}
}
@IBAction func onCreateComment(_ sender: Any)
{
let alertController = UIAlertController(title: "Add Comment", message: nil, preferredStyle: .alert)
alertController.addTextField
{
textField in
textField.placeholder = "Enter your comment here"
}
let postAction = UIAlertAction(title: "Post", style: .default)
{
[weak self] _ in
guard let commenttext = alertController.textFields?.first?.text
else
{
return
}
let newComment = PFObject(className: "Comment")
newComment["author"] = PFUser.current() ?? NSNull()
newComment["text"] = commenttext
newComment["post"] = self?.postObject ?? NSNull()
newComment.saveInBackground
{
[weak self] success, error in
if success
{
self?.loadComments()
}
else if let error = error
{
print("Error saving comment: \(error.localizedDescription)")
}
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(postAction)
alertController.addAction(cancelAction)
present(alertController, animated: true, completion: nil)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return comments.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "CommentCell", for: indexPath) as! CommentCell
let comment = comments[indexPath.row]
cell.commentTextLabel.text = comment["text"] as? String
if let user = comment["author"] as? PFUser
{
cell.nameLabel.text = user.username
}
else
{
cell.nameLabel.text = "Unknown"
}
return cell
}
}
可悲的是,我仍然收到错误 postObject is nil。
更新 3:这是来自
FeedViewController
的一些代码,涉及 postObject
和 CommentViewController
var postObject: PFObject?
//...
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let commentVC = storyboard?.instantiateViewController(withIdentifier: "CommentViewController") as! CommentViewController
if let postObject = postObject
{
commentVC.postObject = postObject
}
present(commentVC, animated: true, completion: nil)
}
```
问题好像出自你
didSelectRowAt
的FeedViewController
方法。继续假设FeedViewController
中的每一行代表一个帖子,您需要获取所选行的帖子对象。
我假设
FeedViewController
在名为 posts
的属性中有一系列帖子(根据您实际使用的内容进行调整)。鉴于此,您的 didSelectRowAt
方法需要类似于以下内容:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let commentVC = storyboard?.instantiateViewController(withIdentifier: "CommentViewController") as! CommentViewController
commentVC.postObject = posts[indexPath.row]
present(commentVC, animated: true, completion: nil)
}
换句话说,获取所选行的帖子对象,就像您在
cellForRowAt
方法中所做的一样。