gpt4 book ai didi

ios - 通过此 segue 将单元格标题从 UITableView 传送到新 ViewController 缺少的命令是什么?

转载 作者:行者123 更新时间:2023-11-28 12:38:22 27 4
gpt4 key购买 nike

我有一个包含 UITableViewViewController。通过以下代码将数据加载到该表中:

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UsernameSentDelegate {

@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var receiveUsername: UILabel!
@IBOutlet weak var userEmailText: UILabel!
var userEmail: String?

var communities = [String]() { didSet { communitiesTableView.reloadData()
}
}
var flag = false

@IBOutlet weak var communitiesTableView: UITableView!

@IBAction func unwindToHome(_ segue: UIStoryboardSegue) {

}

//recieves email address from delegate from LoginViewController
func userLoggedIn(data: String) {

userEmailText.text = data
}

override func viewDidLoad() {
super.viewDidLoad()

self.communitiesTableView.delegate = self
self.communitiesTableView.dataSource = self

}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

return self.communities.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let title = self.communities[indexPath.row]

let cell = UITableViewCell()

cell.textLabel?.text = title

return cell

}

然后我在 UITableView 中设置了 1 个原型(prototype)单元,这样我就可以为我的第二个 View Controller ShowCommunitiesViewController 创建一个 segue,并将这个 segue 命名为 "showCommunitySegue "

ShowCommunitiesViewController 中,我设置了一个标签,可以用作单元格名称的标题,名称为 communityName

ViewController 中,我设置了以下函数来处理 segue,包括所选单元格标题的目标变量。

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

self.performSegue(withIdentifier: "showCommunitySegue", sender: self)
showCommunityController.communityName = //what do I put here?
}

我需要在最后一行添加什么,以便 showCommunityController.communityName 显示单元格标题?

最佳答案

只需在单元格所在的 viewController 中将 selectedCellTitle 声明为 String

var selectedCellTitle: String?

这将是跟踪所选单元格标题的全局变量。

didSelectRowAt中添加如下内容:

      func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Set your global variable to the title
self.selectedCellTitle = self.communities[indexPath.row]
// Trigger your segue
performSegue(withIdentifier: "showCommunitySegue", sender: self)
}

按以下方式覆盖 prepareforsegue 方法:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showCommunitySegue" {
// Check if the segue's destination viewcontroller is your viewcontroller
if let showCommunityController = segue.destination as? ShowCommunityViewController {
// Assign the selected title to communityName
showCommunityController.communityName = self.selectedCellTitle
}
}
}

关于ios - 通过此 segue 将单元格标题从 UITableView 传送到新 ViewController 缺少的命令是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40235890/

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