gpt4 book ai didi

ios - 将数据从一个 TableView 传递到另一个 TableView

转载 作者:搜寻专家 更新时间:2023-11-01 06:44:14 25 4
gpt4 key购买 nike

在我的应用程序中,我有两个表格 View 。第一个 TableView 有一定数量的单元格。这些细胞将永远相同,永远不会改变。

见下文:

enter image description here

上面的表格 View 总是有 3 个单元格,不会更多。在我的服务器上,我有我的 API,其中包含每个单元格的路由。

例如:

获取 - myAPI/游戏

获取 - myAPI/book

获取 - myAPI/旅行

并且每条路由返回不同的数据。

我想要做的是,当用户点击表格 View 单元格时,会将他们带到一个新的表格 View ,其单元格包含来自 API 的响应

目前我的第二个表格 View 是空的,见下图:

enter image description here

这是我到目前为止尝试过的:

 import UIKit

class SectorListTableViewController: UITableViewController {


struct WeatherSummary {
var id: String
}

var testArray = NSArray()
var manuArray = NSArray()

// Array of sector within our company
var selectSector: [String] = ["Game", "Book","Travel"]

override func viewDidLoad() {
super.viewDidLoad()
self.tableView.rowHeight = 80.0




var weatherArray = [WeatherSummary]()
var request = NSMutableURLRequest(URL: NSURL(string: "myAPI")!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "GET"
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
//var params = ["email":"\(emailAdd)", "password":"\(pass)"] as Dictionary<String, String>

var err: NSError?
//request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSArray

UIApplication.sharedApplication().networkActivityIndicatorVisible = true

// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
if(err != nil) {

println(err!.localizedDescription)
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: '\(jsonStr)'")

}
else {

UIApplication.sharedApplication().networkActivityIndicatorVisible = false
// The JSONObjectWithData constructor didn't return an error. But, we should still
// check and make sure that json has a value using optional binding.
var newWeather = WeatherSummary(id:"")

if let parseJSON = json {

for weather in parseJSON {

if let id = weather["employeeName"] as? String{
println(" LOOK HERE \(id)")
newWeather.id = id
}
}

weatherArray.append(newWeather)

self.testArray = parseJSON


}
else {
// Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: \(jsonStr)")

}


}

})



task.resume()

// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false

// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()



}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return self.selectSector.count
}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("sectorList", forIndexPath: indexPath) as! UITableViewCell

// Configure the cell...

if selectSector.count > 0 {

cell.textLabel?.text = selectSector[indexPath.row]
}

return cell
}


/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/

/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/

/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

}
*/

/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/


// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.

if let destination = segue.destinationViewController as? BioListTableViewController {
let indexPath = self.tableView.indexPathForSelectedRow()

if let row:Int = indexPath?.row {


destination.bioArray = testArray




}
}
}
}

生物 ListView Controller 类代码:

import UIKit

struct Note {

var name:String
var job:String
}


class BioListTableViewController: UITableViewController {

private var notes = Array<Note>()

var bioArray = NSArray()
var name = String()

var weather = NSArray()

override func viewDidLoad() {
super.viewDidLoad()

println("THIS IS BIO ARRAY COUNT\(bioArray.count)")
//var weather:WeatherSummary?
var newItem:Note = Note(name: "", job: "")

for x in bioArray {
if let id = x["employeeName"] as? String{
newItem.name = id
}
}

// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false

// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return self.bioArray.count ?? 0
}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("bioCell", forIndexPath: indexPath) as! UITableViewCell

// Configure the cell...

// cell.textLabel?.text = "test"

let weatherSummary: AnyObject = bioArray[indexPath.row]

if let id = weatherSummary["employeeName"] as? String //Dont know the exact syntax.
{
cell.textLabel?.text = id

}

if let job = weatherSummary["jobTitle"] as? String {
cell.detailTextLabel?.text = job

}


return cell
}

}

更新:

这是从 testArray 返回的内容。

enter image description here

最佳答案

您无法让 API 调用处理单元格选择的原因很简单。

这些是异步调用。这意味着他们会在某个时候返回,但不一定很快。事实上,您现在的设计也很糟糕,因为如果您的互联网连接速度很慢,则可能需要很长时间才能加载您的 API。

这是你应该做的。

在您的 BioListTableViewController 中创建一个变量来标识需要调用的 API(也许值得将其设为 enum):

enum NeededAPI {
case Game
case Book
case Travel
case None
}

class BioListTableViewController: UITableViewController {
var apiThatNeedsToBeCalled:NeededAPI = .None {
didSet {
//check which API is set and call the function which will call the needed API
}
}
var bioArray = NSArray() {
didSet {
self.tableView.reloadData()
}
}

您现在要做的是将 API 调用逻辑移至 BioListTableViewController。当用户选择单元格时,您可以为 apiThatNeedsToBeCalled 设置正确的值。执行此操作后,didSet 中的代码将被执行,它应该调用调用适当 API 的函数。

此函数是异步函数,因此它会在完成时返回。当它返回时,你设置

self.bioArray = 结果

触发条件

self.tableView.reloadData()

显然,您的 tableView 需要一个 IBOutlet

关于ios - 将数据从一个 TableView 传递到另一个 TableView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32184378/

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