(此答案与应用架构无关,只是针对作者的问题发布一个简单的解决方案)
您说您的按钮代表模型(个人资料)的“关注”状态。您可能想要一个代表个人资料的模型:
class Profile {
var following : Bool = false
}
您的第一个 ViewController 可能如下所示:
class ProfileListViewController : UIViewController, ProfileDetailsViewControllerDelegate {
var profiles : [Profile] = [...]
func userDidChangeProfileInfo(_ profile : Profile)() {
(...)
}
}
当您打开个人资料时,您会在 ProfileListViewController 中调用类似这样的内容:
func openProfileDetails(at indexPath: IndexPath) {
let profile = profiles[indexPath.row]
let detailsViewController = ProfileDetailsViewController.getInstance()
detailsViewController.profile = profile
detailsViewController.delegate = self
self.navigationController?.pushViewController(detailsViewController, animated: true)
}
delegate 字段是一个看起来像这样的协议,并在上面的代码中实现:
protocol ProfileDetailsViewControllerDelegate : class {
func userDidChangeProfileInfo(_ profile : Profile)
}
ProfileDetailsViewController:
class ProfileDetailsViewController : UIViewController {
var profile: Profile?
weak var delegate : ProfileDetailsViewControllerDelegate?
func didTapFollowButton() {
profile.following = true
delegate?.userDidChangeProfileInfo(profile)
}
}
回到你的ProfileListViewController,delegate 方法将被调用,你可以重新加载你的行(如果你愿意,也可以重新加载整个 tableview):
func userDidChangeProfileInfo(_ profile : Profile)() {
if let row = profiles.firstIndex(where: { $0 == profile }) {
tableView.reloadRows(at: [IndexPath(row: row, section: 0)], with: .automatic)
}
}
接下来将在此索引处重新创建单元格,因此将调用 cellForRowAt 方法。您可以根据模型的变化再次设置您的单元格(更改文本、样式、返回不同的单元格等,无论您的船漂浮并适合您的用例):
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(...)
let profile = profiles[indexPath.row]
if profile.following {
cell.type = .following
} else {
cell.type = .notFollowing
}
return cell
}
单元格本身可能如下所示:
enum ProfileTableCellMode {
case following
case notFollowing
}
class ProfileTableCell : UITableViewCell {
@IBOutlet weak var followButton : UIButton!
var state: ProfileTableCellMode = .notFollowing { //default value
didSet {
onStateUpdated()
}
}
func onStateUpdated() {
switch state {
case .following:
followButton.setTitle("Unfollow", for: .normal)
case .notFollowing:
followButton.setTitle("Follow", for: .normal)
}
}
}
您也可以跳过所有的委派工作,直接在ProfileListViewController 中执行类似的操作:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.tableView.reloadData()
}
所以当ProfileListViewController 重新成为顶级控制器时,整个表会重新加载。
这里最重要的是将 UI(用户界面)与状态(模型等)分开。 UI 应该根据状态呈现/更新自身,并且除了将“我被点击,请处理”传递给逻辑之外,不应处理任何业务逻辑。