gpt4 book ai didi

ios - 如何在单元格上创建一个 "LIKE"按钮并符合 MVC?

转载 作者:行者123 更新时间:2023-11-28 16:07:30 25 4
gpt4 key购买 nike

我想在表格 View 单元格上创建一个点赞按钮,就像 Instagram、Facebook 和其他 100 多个社交网络应用程序所做的那样,但我正在努力理解如何正确地做到这一点,同时牢记 MVC 范例。

我的结构是这样的:

Model - FeedPost class 
View - FeedCell class (UITableViewCell subclass)
Controller - FeedTableViewController class (UITableViewController subclass)

首先想到的是执行以下操作:

在 FeedCell.swift 中:

@IBAction func likeButtonPressed(_ sender: AnyObject) {
if let button = sender as? UIButton {
post.like(completed: {
if(completed){
button.isSelected = !button.isSelected
}
})
}
}

在 FeedPost.class 中:

func like(completed: (Bool) -> Void ) {
//Make a request to a server and when it is done call
completed(true)
}

但这肯定会破坏 MVC 模式,因为我从 View 访问我的模型。所以我可能想使用我的数据并通过 View Controller 查看。 View Controller 存储帖子数组。所以我想做以下事情: - 响应用户按下表格 View 单元格上的按钮 - 找出哪个帖子被点赞 - 执行传递帖子 ID 或任何其他引用的服务器请求 - 成功完成请求后,将按钮状态更改为选中

在遵循 MVC 模式时,您将如何做到这一点?

任何以正确方式完成此操作的示例或开源项目都将受到高度赞赏。

最佳答案

怎么样:

FeedCell.swift:

@IBOutlet var likeButton: UIButton!
var likeButtonPressedHandler: (() -> ())?
var isLikeButtonSelected: Bool {
get { return likeButton.isSelected }
set { likeButton.isSelected = newValue }
}
@IBAction func likeButtonPressed(_ button: UIButton) {
likeButtonPressedHandler?()
}

FeedPost.class:

func like(completion: (Bool) -> Void ) {
//Make a request to a server and when it is done call
completion(true)
}

View Controller (UITableViewDataSource):

var posts: [FeedPost]

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier", for: indexPath) as? FeedCell
let post = posts[indexPath.row]
cell.isLikeButtonSelected = post.isLiked
cell.likeButtonPressedHandler = { [weak cell] in
post.like { completed in
if let cell = cell where completed {
cell.isLikeButtonSelected = !cell.isLikeButtonSelected
}
})
}
return cell
}

关于ios - 如何在单元格上创建一个 "LIKE"按钮并符合 MVC?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40059280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com