在 SWIFT 中使用 NSDictionary 填充 UITable [英] Populating a UITable with NSDictionary in SWIFT
问题描述
我有一个从 JSON 请求中检索的字典,我想用这些值填充一个表.我认为一切都很好,但是我在类声明中收到一个错误 Type SubjectsViewController 不符合协议 'UITableViewDataSource'
我正在使用故事板,并且我在 UI 上添加了表格视图datasource
和 delegate
据我所知,我正在正确地实现这些功能.我在下面添加了代码的相关部分.
I have a dictionary that I retrieve from a JSON request and I would like to populate a table with those values. I think everything is okay, however I am getting an error in the class declaration that Type SubjectsViewController does not conform to protocol 'UITableViewDataSource'
I am using a storyboard, and I added the table view on the UI to datasource
and delegate
and as far as I know, I am implementing the functions correctly. I have added the relevant parts of my code below.
查看 this 可能有用,这是我发布的问题了解我为什么使用回调.提前致谢!
It may be useful to see this which is a question I posted to understand why I am using the callback. Thanks in advance!
class SubjectsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
override func viewDidLoad() {
super.viewDidLoad()
getSubjects(callback: {(resultValue)-> Void in
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return resultValue.count
}
func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
cell.textLabel?.text = resultValue[indexPath.row] as! String?
return cell
}
})
}
// Initialise components of the view
let UserDetails = UserDefaults.standard.stringArray(forKey: "UserDetailsArray") ?? [String]()
@IBOutlet weak var tableView: UITableView!
// Function to retrieve the subjects for the user
func getSubjects(callback: @escaping (NSDictionary)-> Void){
let myUrl = NSURL(string: "www.mydomain.com/retrieveSubjects.php");
let request = NSMutableURLRequest(url:myUrl as! URL)
let user_id = UserDetails[0]
request.httpMethod = "POST";
let postString = "user_id=\(user_id)";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request as URLRequest){
data, response, error in
if error != nil {
print("error=\(error)")
return
}
var err: NSError?
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
let resultValue: NSDictionary = parseJSON["subjects"] as! NSDictionary
callback(resultValue)
}
} catch let error as NSError {
err = error
print(err!);
}
}
task.resume();
}
}
编辑:在解开一个可选值时,CLASS 抛出意外发现 nil
EDIT: CLASS throwing unexpectedly found nil while unwrapping an optional value
class SubjectsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var dataDict: [String:AnyObject]?
@IBOutlet var tableView: UITableView!
let userDetails: [String] = UserDefaults.standard.stringArray(forKey:"UserDetailsArray")!
override func viewDidLoad() {
super.viewDidLoad()
self.dataDict = [String:AnyObject]()
self.tableView.delegate = self
self.tableView.dataSource = self
self.getSubjects()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataDict!.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.value1, reuseIdentifier: "cell")
let array = self.dataDict?[String(indexPath.row)] as! [String]
print(array)
cell.textLabel?.text = array[0]
cell.detailTextLabel?.text = array[1]
return cell
}
func getSubjects() {
let myUrl = NSURL(string: "www.mydomain/retrieveSubjects.php");
let request = NSMutableURLRequest(url:myUrl as! URL)
let user_id = userDetails[0]
request.httpMethod = "POST";
let postString = "user_id=\(user_id)";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
var err: NSError?
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
let resultValue = parseJSON["subjects"] as! [String:AnyObject]
self.dataDict = resultValue
self.tableView.reloadData()
}
} catch let error as NSError {
err = error
print(err!);
}
}
task.resume();
}
}
推荐答案
以下是您需要做的:
首先,为您的数据创建一个类变量.把它放在你的类声明下:
First, create a class variable for your data. Put this under your class declaration:
var dataDict: [String:AnyObject]?
然后,为了使事情井井有条,请将您的 tableView 属性和您的 userDetails 属性直接放在 dataDict 下.
Then, to keep things organized, put your tableView property and your userDetails property directly under the dataDict.
@IBOutlet var tableView: UITableView!
let userDetails: [String] = UserDefaults.standard.stringArray(forKey:"UserDetailsArray")
现在,您的 viewDidLoad 方法应如下所示:
Now, your viewDidLoad method should look like this:
override func viewDidLoad() {
super.viewDidLoad()
self.dataDict = [String:AnyObject]()
self.tableView.delegate = self
self.tableView.dataSource = self
self.getSubjects()
}
在此之下,您需要处理 UITableViewDataSource 方法:
Below that, you'll want to take care of the UITableViewDataSource methods:
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataDict.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.value1, reuseIdentifier: "cell")
if let array = self.dataDict[String(indexPath.row)] as? [String] {
cell.textLabel?.text = array[0]
cell.detailTextLabel?.text = array[1]
}
return cell
}
最后,您需要实现 getSubjects()
方法:
Lastly, you need to implement the getSubjects()
method:
func getSubjects() {
let myUrl = NSURL(string: "www.mydomain.com/retrieveSubjects.php");
let request = NSMutableURLRequest(url:myUrl as! URL)
let user_id = UserDetails[0]
request.httpMethod = "POST";
let postString = "user_id=\(user_id)";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
var err: NSError?
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
let resultValue = parseJSON["subjects"] as! [String:AnyObject]
self.dataDict = resultValue
self.tableView.reloadData()
}
} catch let error as NSError {
err = error
print(err!);
}
}
task.resume();
}
总而言之,您的代码应如下所示:
Altogether, your code should look like this:
class SubjectsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var dataDict: [String:AnyObject]?
@IBOutlet var tableView: UITableView!
let userDetails: [String] = UserDefaults.standard.stringArray(forKey:"UserDetailsArray")
override func viewDidLoad() {
super.viewDidLoad()
self.dataDict = [String:AnyObject]()
self.tableView.delegate = self
self.tableView.dataSource = self
self.getSubjects()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataDict.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.value1, reuseIdentifier: "cell")
if let array = self.dataDict[String(indexPath.row)] as? [String] {
cell.textLabel?.text = array[0]
cell.detailTextLabel?.text = array[1]
}
return cell
}
func getSubjects() {
let myUrl = NSURL(string: "www.mydomain.com/retrieveSubjects.php");
let request = NSMutableURLRequest(url:myUrl as! URL)
let user_id = UserDetails[0]
request.httpMethod = "POST";
let postString = "user_id=\(user_id)";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
print("error=\(error)")
return
}
var err: NSError?
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
let resultValue = parseJSON["subjects"] as! [String:AnyObject]
self.dataDict = resultValue
self.tableView.reloadData()
}
} catch let error as NSError {
err = error
print(err!);
}
}
task.resume();
}
}
这篇关于在 SWIFT 中使用 NSDictionary 填充 UITable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!