【问题标题】:Swift Json count and create TableViewSwift Json 计数并创建 TableView
【发布时间】:2015-09-14 10:26:41
【问题描述】:

我需要创建一个 tableview 并用我使用 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"
    }
]
}

这是 3 个不同的新闻,标题等,所以我需要计算它,因为我将添加新的,并在此基础上创建一个表格视图。

这是我现在使用新 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")

                        }
                    }
                }
            }










        }




    }


}

对于 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

点击单元格时如何在第二页显示说明?

谁能帮帮我?提前致谢。

【问题讨论】:

    标签: ios json swift


    【解决方案1】:

    按照以下步骤呈现您的表格视图:

    假设您已将视图控制器设置为 UITableViewController 的数据源和委托。

    1. 在您的表视图控制器的子类中:在 loadView 或 viewWillAppear 内部进行服务器调用以获取详细信息。 [这你可能已经在做]
    2. 创建一个全局参数来保存该数据。例如self.vehicles = jsonData["news"]
    3. 服务器响应后,在self.tableView 上调用reloadDatamethod。这将触发对您的表数据源方法的调用 - numberOfRowsInSection:cellForRowAtIndexPath: 等。
    4. 从数据源方法返回正确的值。根据您的需要,您可以创建一个自定义单元格并使用self.vehicles 在其上获取和呈现数据。

    编辑: 示例

    您的数据是一个字典数组,其中数组计数将驱动表格中的单元格数。也就是说,假设您的数组中有 5 个字典,因此您有 5 个单元格。当您接到cellForRowAtIndexPath: 的电话时,请使用“index path.row”来获取映射到请求中单元格的正确字典。现在,获取该字典中的值并将它们设置在单元格上。像这样:

    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
    }
    

    类似地实现didSelectRowAtIndexPath,然后获取描述并将其传递给您的目标视图控制器进行显示。

    编辑 2(根据 OP 请求):

    基于第二个屏幕设计(表格控制器或简单视图控制器),创建一个新的控制器类。然后,正如我上面提到的,实现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)
    }
    

    一些参考资料:

    Apple Docs on UITableViewController

    Handling UITableViewController Programmatically

    【讨论】:

    • 对不起,我不是 tableview 专家。我可以创建一个,但我不明白步骤
    • 基本上,[self.tableView reloadData] 是这里的关键。在你从服务器调用这个数据之后,然后你有关于 UITableViews 的任何基本知识,将它转换成代码,你应该能够渲染它。我已经更新了我的帖子,其中包含您可能已经浏览过的几个链接,但仅供需要时参考。
    • 这里的问题是如何获取不同的新闻并将其放在表格视图中,那么我如何获得所有新闻的标题并将其作为表格视图的标题
    • 能否请您简要说明您想将所有这些数据放在哪里。例如标题将在每个单元格textLabel,描述将在每个单元格detailTextLabel 等。
    • 点击单元格时,描述将在另一个页面中
    【解决方案2】:

    news 的对象是Array(字典),而不是Dictionary

    if let vehicles = jsonData["news"] as? NSArray {
       for vehicle in vehicles {
          let vehiclesKeys = vehicle.allKeys
             println(vehiclesKeys)
             println("123")
            }
        }
    }
    

    vehicles.count 为您提供数组中的项目数。

    【讨论】:

    • 非常感谢,您知道我如何将所有信息放在表格视图上吗??
    • vehicles的值作为数据源放入实例变量中,使用所需方法实现UITableViewDataSource协议,iOS中如何填充表格视图的教程数以百万计
    • 是的,是的,我知道如何创建表格视图,但这更复杂,因为我需要像新闻一样创建单元格
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    • 1970-01-01
    相关资源
    最近更新 更多