协助区分 URL 和 Tableview 数据

Assistance with differentiating URLs and Tableview Data

免责声明,新内容:我正在开发一个应用程序,它为 TableView 中的每个项目提供不同的资源。当用户做出选择时,应用程序会进入一个新的 ViewController。虽然 viewController 对于每个 TableView 选择都是相同的,但其中的 URL 按钮应该有不同的 URL 对应于 tableview 选择。

我无法为每个 tableView 数组 [第 0 周到第 8 周] 编写不同的 URLS。现在,View Controller 中的按钮对于每个 tableview 选择具有相同的 URLS。希望我解释得足够清楚,但附上了代码。如果需要更多信息,请告诉我。谢谢!

import UIKit

class WeekTableViewController: UITableViewController {



    var week = [
    "Week 0:",
    "Week 1:",
    "Week 2:",
    "Week 3:",
    "Weel 4:",
    "Week 5:",
    "Week 6:",
    "Week 7:",
    "Week 8:"]

    override func viewDidLoad() {
        super.viewDidLoad()


    }





    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

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

        return week.count
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let selectedWeek = week[indexPath.row]
        performSegue(withIdentifier:"moveToWeekDetail", sender:selectedWeek)
    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel?.text = week[indexPath.row]
        return cell

    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?){
        if let weekViewController = segue.destination as? WeekDetailViewController{
            if let selectedWeek = sender as? String{
                weekViewController.title = selectedWeek
            }
        }
    }

将一周的描述从简单的字符串更改为结构:

/// A struct to hold information about each week
/// Add more properties as needed
struct WeekInfo {
    let description: String
    let url: URL
}

class WeekTableViewController: UITableViewController {
    // It's no longer an array of strings
    var week = [
        WeekInfo(description: "Week 1", url: URL(string: "https://somewhere.com")!),
        WeekInfo(description: "Week 2", url: URL(string: "https://somewhere.com")!),
        WeekInfo(description: "Week 3", url: URL(string: "https://somewhere.com")!),
    ]

    // ...

    override func prepare(for segue: UIStoryboardSegue, sender: Any?){
        if let weekViewController = segue.destination as? WeekDetailViewController{
            // Pass the week's info onto the detail view controller
            if let selectedWeek = sender as? WeekInfo {
                weekViewController.title = selectedWeek.description
                weekViewController.week = selectedWeek
            }
        }
    }
}

class WeekDetailViewController: UIViewController {
    // Info about the week
    var week: WeekInfo!
}