在Swift中用NSDictionary JSON填充UITableView
我是新鲜的。我叫API,我得到的请求和数据的响应。但是,我不知道如何填充数据从NSDictionary到TableviewCell.Can任何人都可以帮助我。
代码在这里:
var responseData:NSString =NSString(data:data!,encoding:NSUTF8StringEncoding)! println("Response Data is "+responseData) var error: NSError? let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary println("NSDictionary JSON Is",jsonData) var error1: NSError? var dict: NSDictionary =["Book_name":" "] } }
我的回应数据是:
Response Data is {"ListOfBooks":[{"Book_name":"javascript_tutorial"}]} (NSDictionary JSON Is, [ListOfBooks: ({"Book_name" = "javascript_tutorial"; } )])
如何将文件名“javascript_tutorial”列入tableview?
let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary if jsonData { // process jsonData var arrayofBOOKs: NSArray = jsonData["ListOfBooks"] as NSArray for elem: AnyObject in arrayofBOOKs { let name = elem["Book_name"] as String println("Book_name: \(name)") // here add the string to array items.addObject(name) } tableView.reloadData } else { // couldn't load JSON, look at error }
以下是要遵循的步骤:
步骤1
打开ViewController.swift
类,并在类声明下添加一个新的tableview实例variables
@IBOutlet var tableView: UITableView!
第2步
为了符合UITableViewDelegate
和UITableViewDataSource
protocol
只需在类声明中的UIViewController之后用冒号分隔它们即可
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { override func viewDidLoad() { super.viewDidLoad() var items = NSMutableArray() self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") }
第3步
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell cell.textLabel?.text = items[indexPath.row] return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { println("You selected cell #\(indexPath.row)!") }
- 如何解决Cocoa touch框架中的符号名称冲突
- swift 2.1 alamofire timeout方法
- 如何在Swift中使用Storyboard在UITabBarController中使用导航控制器
- 为什么Swift的AVPlayer会在一次播放中加载playerItem两次?
- 如何使用Swift实时过滤video
- 无法使用types为“(NSMutableURLRequest,(_,_,_)throws – > _”)的参数列表调用“dataTaskWithRequest”
- 如何从纯C函数返回值到swift?
- ios swift:Tableview“un”-checkmark cell
- 如何根据十进制值设置货币格式?