ios - Swift 3 - 根据单击的单元格在 TableViewController swift 文件中设置变量

标签 ios json uitableview swift3

我正在尝试根据单击 tableView 中的哪个单元格来设置字符串。 BlueLineTableViewController 应该捕获用户的点击。

import UIKit

class BlueLineTableViewController: UITableViewController {

override func viewDidLoad() {
    super.viewDidLoad()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}

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

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return bluelinestations.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "bluelinecell", for: indexPath)

    let station = bluelinestations[indexPath.row]
    cell.textLabel?.text = station.name
    cell.imageView?.image = UIImage(named: station.image)
    return cell
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let row = indexPath.row
    if row == 0 {
        BlueBelmontTableViewController().feed = "http://lapi.transitchicago.com/api/1.0/ttarrivals.aspx?key=mykey&mapid=40890&outputType=JSON"
    }
    if row == 1   {
        BlueBelmontTableViewController().feed="http://lapi.transitchicago.com/api/1.0/ttarrivals.aspx?key=mykey&mapid=40820&outputType=JSON"
    }
}

BlueBelmontTableViewController 的 feed 变量应该更改/设置为另一个 url,具体取决于在 BlueLineTableViewController 中单击的单元格。

import UIKit

class BlueBelmontTableViewController: UITableViewController {

class Destinations {
    var destination: String = ""
    var time: String = ""
}

var feed = ""

var dataAvailable = false

var records = [Destinations]()

override func viewDidLoad() {
    super.viewDidLoad()
    parseData()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

    for r in records {
        r.time = ""
        r.destination = ""
    }
}

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

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return dataAvailable ? records.count : 15
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if (dataAvailable) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        let destinationRow = records[indexPath.row]
        cell.textLabel?.text = destinationRow.destination
        cell.detailTextLabel?.text = destinationRow.time
        return cell
    } else {
        let cell = tableView.dequeueReusableCell(withIdentifier: "PlaceholderCell", for: indexPath)
        return cell
    }
}

func parseData() {
    guard let feedURL = URL(string: feed) else {
        return
    }
    let request = URLRequest(url: feedURL)
    let task = URLSession.shared.dataTask(with: request) {(data, response, error) in
        if error != nil
        {
            print("Error")
        }
        else {
            if let content = data {
                do {
                    let json = try JSONSerialization.jsonObject(with: content, options: []) as? [String:Any] ?? [:]
                    print(json)
                    if let ctattimetable = json["ctatt"] as? [String:Any] {
                        if let estArrivalTime = ctattimetable["eta"] as? [[String:Any]] {
                            for item in estArrivalTime{
                                if let headingTowards = item["destNm"] as? String,
                                    let arrivalTime = item["arrT"] as? String {
                                    let record = Destinations()
                                    record.destination = headingTowards
                                    record.time = arrivalTime
                                    self.records.append(record)
                                }
                                self.dataAvailable = true
                                DispatchQueue.main.async {
                                    self.tableView.reloadData()
                                }

                            }
                        }
                    }
                }
                catch {
                }
            }
        }
    }
    task.resume()
}
}

我已经尝试根据 indexPath.row 在 didSelectRowAt 方法中设置 url,如 BlueLineTableViewController 中所示,但它似乎没有做任何事情。有人知道我会怎么做吗?

下面是我项目这部分的Main.storyboard:

enter image description here

最佳答案

您无法传递值,因为您正在设置 feed BlueBelmontTableViewController 的全新实例的属性不是使用您的 segue 添加到导航堆栈中的那个您从 UITableViewCell 创建的至 BlueBelmontTableViewController .

您需要做的是覆盖 prepareForSegue在你的BlueLineTableViewController将您的值(value)传递给 BlueBelmontTableViewController .

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let vc = segue.destination as! BlueBelmontTableViewController
    if let indexPath = self.tableView.indexPathForSelectedRow {
        if indexPath.row == 0 {
           vc.feed = "http://lapi.transitchicago.com/api/1.0/ttarrivals.aspx?key=mykey&mapid=40890&outputType=JSON"
        }
        if indexPath.row == 1   {
            vc.feed = "http://lapi.transitchicago.com/api/1.0/ttarrivals.aspx?key=mykey&mapid=40820&outputType=JSON"
        }  
    }
}

关于ios - Swift 3 - 根据单击的单元格在 TableViewController swift 文件中设置变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44105108/

相关文章:

ios - 如何在 Swift 的表格 View 单元格中进行有限的多重复选标记?

iphone - 当单元格突出显示时,uibutton 图像不会改变

c# - UIRefreshControl 显示在 UICollectionViews 单元格上方

iphone - UIWebView 不会加载某些网站

java - 解析csv数据并转换为嵌套json java

c++向网络服务器上的API发送请求然后接收json数组响应?

ios - [Swift]如何将字符串分配给 UITextField?

ios - 在 Swift 中,为什么 "let _ = this"比 "this != nil"快?

json - 根据内容重命名 JSON 文件

ios - 为什么 tableview 单元格在要重复使用时开始闪烁?