Swift 3 - 根据单击的单元格在 TableViewController swift 文件中设置变量
Posted
技术标签:
【中文标题】Swift 3 - 根据单击的单元格在 TableViewController swift 文件中设置变量【英文标题】:Swift 3 - Setting variable in TableViewController swift file depending on cell clicked 【发布时间】:2017-05-22 05:17:41 【问题描述】:我正在尝试根据单击 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 变量应根据在 BlueLineTableViewController 中单击的单元格更改/设置为另一个 url。
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()
我尝试根据在 BlueLineTableViewController 中看到的 indexPath.row 在 didSelectRowAt 方法中设置 url,但它似乎没有做任何事情。有人知道我会怎么做吗?
下面是我项目这一部分的 Main.storyboard:
【问题讨论】:
【参考方案1】:您无法传递值,因为您将feed
属性设置为BlueBelmontTableViewController
的全新实例,而不是使用您从UITableViewCell
创建的segue
添加到导航堆栈中的那个实例到BlueBelmontTableViewController
。
您需要做的是在您的BlueLineTableViewController
中覆盖prepareForSegue
以将您的值传递给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"
【讨论】:
非常感谢!我必须这样做 if let indexPath = self.tableView.indexPathForSelectedRow?.row 才能工作,否则它工作得很好(不确定它是否重要,但我把它变成了 switch 语句,比如 switch index case 0: vc .feed = "url" 等 @moesyzlack23 欢迎朋友 :),不要那样写,检查我编辑的答案并将您的条件更改为indexPath.row
,你们都准备好了
@moesyzlack23 两者都是相等的,但你的一个将进入可选链接,因为indexPath
是可选的,所以row
也是可选的,因为我刚刚检查了indexPath
。
知道了,你是最棒的!
@moesyzlack23 很高兴你理解队友:)【参考方案2】:
而不是
BlueBelmontTableViewController().feed = "http://lapi.transitchicago.com/api/1.0/ttarrivals.aspx?key=mykey&mapid=40890&outputType=JSON"
使用
self.feed = "http://lapi.transitchicago.com/api/1.0/ttarrivals.aspx?key=mykey&mapid=40890&outputType=JSON"
因为 BlueBelmontTableViewController() 正在初始化 BlueBelmontTableViewController 的新实例,并且您想更改已有的实例,因此您应该使用 self 而不是创建新实例。
【讨论】:
以上是关于Swift 3 - 根据单击的单元格在 TableViewController swift 文件中设置变量的主要内容,如果未能解决你的问题,请参考以下文章
UICollectionView 单元格在swift中使用约束固定宽度和动态高度
UITableView 中的单元格在 iOS 中选择之前不会更新(swift)