[英]Swift Json count and create TableView
I need to create a tableview and fill that with database information that I take with json. 我需要创建一个表视图,并用我使用json获取的数据库信息进行填充。 This is the response I get from the database with json
这是我从json从数据库中获得的响应
{
"news": [
{
"id": "35",
"type": "news",
"title": "final test for offer",
"city": "Mumbai",
"description": "Test description",
"image": "http://www.saimobileapp.com/mobileappbackend/news/IMG_0421.JPG"
},
{
"id": "31",
"type": "news",
"title": "new test",
"city": "Mumbai",
"description": "yes its a test msg",
"image": "http://www.saimobileapp.com/mobileappbackend/news/Chrysanthemum.jpg"
},
{
"id": "30",
"type": "news",
"title": "This is a test news",
"city": "Mumbai",
"description": "Test description",
"image": "http://www.saimobileapp.com/mobileappbackend/news/1.jpg"
}
]
}
These are 3 different news with title etc., so I need to count it as I will add new, and create a table view in base of that. 这是3个带有标题等的不同新闻,因此我需要对其进行计数,因为我将添加新消息,并在此基础上创建一个表格视图。
This is my code now to get the database information with new EDIT: 这是我现在使用新的EDIT获取数据库信息的代码:
func LoadNews() {
let post:NSString = ""
NSLog("PostData: %@",post);
let url:NSURL = NSURL(string: "http://saimobileapp.com/services/sai_news.php")!
let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
let postLength:NSString = String( postData.length )
let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
var reponseError: NSError?
var response: NSURLResponse?
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)
if ( urlData != nil ) {
let res = response as! NSHTTPURLResponse!;
NSLog("Response code: %ld", res.statusCode);
if (res.statusCode >= 200 && res.statusCode < 300)
{
let responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
NSLog("Response ==> %@", responseData);
var error: NSError?
var Title: [String] = []
if let jsonData = NSJSONSerialization.JSONObjectWithData(urlData!, options: nil, error: &error) as? [String:AnyObject] { // dictionary
if let locationsArray = jsonData["news"] as? [[String:AnyObject]] { // array of dictionaries
for locationDictionary in locationsArray { // we loop in the array of dictionaries
if let location = locationDictionary["title"] as? String { // finally, access the dictionary like you were trying to do
Title.append(location)
var SaveTitle = save.setObject(Title, forKey: "NewsTitle")
}
}
}
}
}
}
}
And for TableView i use that now : 对于TableView,我现在使用它:
// MARK: UITextFieldDelegate Methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var FormName = save.arrayForKey("NewsTitle")!
return FormName.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var FormName = save.arrayForKey("NewsTitle")!
var cell:UITableViewCell = self.TableView.dequeueReusableCellWithIdentifier("Cell") as! UITableViewCell
let row = indexPath.row
cell.textLabel?.text = FormName[indexPath.row] as! String
if (indexPath.row % 2 == 0) {
cell.backgroundColor = UIColor.clearColor()
}else{
cell.backgroundColor = UIColor.clearColor()
cell.textLabel?.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.0)
}
cell.textLabel?.textColor = UIColor.whiteColor()
return cell
}
// MARK: UITableViewDelegate Methods
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
TableView.deselectRowAtIndexPath(indexPath, animated: false)
let row = indexPath.row
How can i show the description in the second page when i tap on the cell? 当我点击单元格时,如何在第二页中显示说明?
Can anyone please help me? 谁能帮帮我吗? Thanks in advance.
提前致谢。
The object of key news
is an Array
(of dictionaries), not a Dictionary
关键
news
的对象是(字典的) Array
,而不是Dictionary
if let vehicles = jsonData["news"] as? NSArray {
for vehicle in vehicles {
let vehiclesKeys = vehicle.allKeys
println(vehiclesKeys)
println("123")
}
}
}
vehicles.count
gives you the number of items in the array. vehicles.count
提供数组中的项目数。
Follow these steps to render your table view: 请按照以下步骤呈现表格视图:
Assuming you have set your view controller as datasource and delegate for UITableViewController. 假设您已将视图控制器设置为数据源并为UITableViewController委托。
self.vehicles = jsonData["news"]
self.vehicles = jsonData["news"]
reloadData
method on self.tableView
. self.tableView
上调用reloadData
方法。 This will trigger calls to your table data sources methods - numberOfRowsInSection:
, cellForRowAtIndexPath:
etc. numberOfRowsInSection:
, cellForRowAtIndexPath:
等。 self.vehicles
to fetch & render data on it. self.vehicles
来获取和呈现其上的数据。 Edit: Example 编辑: 示例
Your data is a array of dictionary where array count will drive the number of cells in the table. 您的数据是一个字典数组,其中数组计数将驱动表中的单元格数。 That said, lets say there are 5 dictionaries in your array so you have 5 cells.
也就是说,可以说数组中有5个字典,所以您有5个单元格。 When you get a call on
cellForRowAtIndexPath:
, use 'index path.row' to get the right dictionary mapped to the cell in request. 当您调用
cellForRowAtIndexPath:
,请使用“ index path.row”来获取映射到请求中单元格的正确字典。 Now, fetch the values inside that dictionary and set them on cell. 现在,获取该词典中的值并将其设置在单元格上。 Like this:
像这样:
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
// Configure the cell...
let cellId: NSString = "Cell"
var cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellId) as UITableViewCell
if let ip = indexPath {
var data = self.vehicles[ip.row] as NSDictionary
cell.textLabel.text = data.valueForKey("title") as String
}
return cell
}
Similarly implement didSelectRowAtIndexPath
and then fetch & pass on description to your target view controller for display. 类似地,实现
didSelectRowAtIndexPath
,然后获取描述并将其传递给目标视图控制器以进行显示。
Edit 2 (On OP request): 编辑2(根据OP请求):
Based on second screen design (table controller or simple view controller), create a new controller class. 基于第二个屏幕设计(表控制器或简单视图控制器),创建一个新的控制器类。 Then, as I mentioned above, implement
didSelectRowAtIndexPath
something like below: 然后,如上所述,实现
didSelectRowAtIndexPath
如下所示:
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var description = String()
if let ip = indexPath {
var data = self.vehicles[ip.row] as NSDictionary
description = data.valueForKey("description") as String
}
var descriptionVC = SecondScreenVC(withDescription: description)
self.navigationController.pushViewController(descriptionVC, animated: true)
}
Some references: 一些参考:
Apple Docs on UITableViewController UITableViewController上的Apple文档
Handling UITableViewController Programmatically 以编程方式处理UITableViewController
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.