简体   繁体   English

如何在 iOS ZAE832E9B5BDA265956DB45F3FA6AAA8

[英]How to parse value from nested json into tableview cell with multiple label in iOS Swift

I have tableView with a cell of multiple labels.我有一个带有多个标签的单元格的 tableView。 Having cell-like, set-1 variableName1, variablevalue1 & set-2 variableName2, variablevalue2 .具有类似单元格的 set-1 variableName1, variablevalue1 & set-2 variableName2, variablevalue2 Here all the data will get from JSON responses including the title label.这里所有的数据都来自 JSON 响应,包括标题 label。

I have stored all values to model and showing some data in tableView.我已将所有值存储到 model 并在 tableView 中显示一些数据。 but I could not able to show the multiple label values alone.但我无法单独显示多个 label 值。

Here is my JSON structure for multiple labels:这是我的多个标签的 JSON 结构:

    "_embedded": {
                "variable": [
                    {
                        "_links": {
                            "self": {
                                "href": ""
                            }
                        },
                        "_embedded": null,
                        "name": "startedBy",
                        "value": "Preethi",
                        "type": "String",
                        "valueInfo": {}
                    },
                    {
                        "_links": {
                            "self": {
                                "href": ""
                            }
                        },
                        "_embedded": null,
                        "name": "LoanAmount",
                        "value": "1500000",
                        "type": "String",
                        "valueInfo": {}
                    }
                ]
            },

Here I am trying to show the value from the variable array -> name & value.在这里,我试图显示来自变量数组的值 -> 名称和值。

Tried so far like this:到目前为止尝试过这样的:

       for val in (t._embedded?.variable)!{
        
        print("val name", val.name ?? "")
        print("val name", val.value ?? "")
        

        
        if val.name == val.name {

            cell.variableName1.text = val.name
            cell.variablevalue1.text = val.value
        }


        if val.value == val.value {

            cell.variableName2.text = val.name
            cell.variablevalue2.text = val.value

        }
    }

here the image of the tableView cell:这里是 tableView 单元格的图像:

在此处输入图像描述

Any help much appreciated pls...任何帮助非常感谢请...

You can use TableView in CollectionView您可以在 CollectionView 中使用 TableView

import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {

//MARK: - Variable Declaration
let arryOfData = [["name": "startedBy","value": "Preethi"],["name": "LoanAmount","value": "1500000"]]
//MARK: - IBOutlet
@IBOutlet weak var tblView:UITableView!
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}

// MARK: - UITableview DELEGATE AND DATASOURCE
func numberOfSections(in tableView: UITableView) -> Int {
    return 1 // If you more data than use dynamic count set
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tblView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ListCell
    cell.clcView.reloadData()
    return cell
}

// MARK: - UICOLLECTION DELEGATE AND DATASOURCE
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return self.arryOfData.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath)
    let lblName = cell.viewWithTag(101) as! UILabel
    let lblValue = cell.viewWithTag(102) as! UILabel
    lblName.layer.borderWidth = 1
    lblName.layer.borderColor = UIColor.lightGray.cgColor
    lblValue.layer.borderWidth = 1
    lblValue.layer.borderColor = UIColor.lightGray.cgColor
    let dict = self.arryOfData[indexPath.row]
    lblName.text = dict["name"] ?? ""
    lblValue.text = dict["value"] ?? ""
    return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let spacing:CGFloat = 10
    let numberOfItemsPerRow:CGFloat = 2
    let spacingBetweenCells:CGFloat = 10
    let totalSpacing = (2 * spacing) + ((numberOfItemsPerRow) * spacingBetweenCells)
    let productWidth = (collectionView.bounds.width - totalSpacing)/numberOfItemsPerRow
    return CGSize(width: productWidth, height: 110)
    
   }
}

class ListCell: UITableViewCell {
    //MARK: - Variable Declaration
    
    //MARK: - IBOutlet
    @IBOutlet weak var clcView:UICollectionView!
    
    //MARK: - LifeCycle
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
    //MARK: - IBAction

 }

你的输出

for val in (t._embedded?.variable)!{
    

    if val.name == val.name {

        cell.variableName1.text = val.name
        cell.variablevalue1.text = val.value
    }


    if val.value == val.value {

        cell.variableName2.text = val.name
        cell.variablevalue2.text = val.value

    }
}

If you compare val.name == val.name it always returns true so you need to modify like this val.name == "startedBy" and for value val.value == "1500000" to display the first item and second item of the json.如果你比较val.name == val.name它总是返回 true 所以你需要像这样修改val.name == "startedBy"和值val.value == "1500000"以显示第一项和第二项json。

Anyway where do you call the for loop?无论如何,您在哪里调用 for 循环? I think you want to display each item of the json in a unique cell so you need to parse the json into a dictionary and use it in the "cellForItemAt" function of CollectionViewDataSource我认为您想在唯一的单元格中显示 json 的每个项目,因此您需要将 json 解析为字典并在 CollectionViewSource 的“cellForItemAt”function 中使用它

There is little information on what you really want but maybe this can help.关于您真正想要什么的信息很少,但也许这会有所帮助。

Case 1情况1

I feel like your json may not be properly defined.我觉得您的 json 可能没有正确定义。 If it is, then it seems to say that you will only have one set of two variables, then you wouldn't need a UITableView because there would be only one cell, that way you could accomplish that by just adding one UIView to your current view.如果是这样,那么似乎您将只有一组两个变量,那么您就不需要UITableView因为只有一个单元格,这样您就可以通过将一个UIView添加到当前看法。

If you:如果你:

  • will always have only two variables in the json json 中总是只有两个变量
  • want to show their content in one cell想在一个单元格中显示他们的内容
  • are using UITableView正在使用 UITableView

On cellForRow(at:) you cancellForRow(at:)你可以

func cellForRow(at indexPath: IndexPath) -> UITableViewCell {

    guard let cell = self.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath) else { return UITableViewCell() }

    for val in (t._embedded?.variable)! {
        
        // The if you had here is always true
        cell.variableName1.text = val.name
        cell.variablevalue1.text = val.value

        cell.variableName2.text = val.name
        cell.variablevalue2.text = val.value
        }
    }

    return cell
}

Case 2案例二

If your json is properly defined but you will have more than two variables and you want to show two per row then I would suggest you used UICollectionViewCell and have your cells take half the screen in size each and in each one you show the value of the proper index.如果您的 json 定义正确,但您将有两个以上的变量,并且您希望每行显示两个,那么我建议您使用UICollectionViewCell并让您的单元格在每个屏幕中占据屏幕的一半,并且在每个您显示的值适当的索引。 Something like this:像这样的东西:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath),
          cellInfo = t._embedded?.variable[indexPath.item] else { return UICollectionViewCell() }

    cell.variableName.text = cellInfo.name
    cell.variableValue.text = cellInfo.value

    return cell
}

// MARK: Size of the cells
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let midWidthPoint = UIScreen.main.bounds.size.width / 2

    return CGSize(width: midWidthPoint, height: 100)
}

Case 3案例3

If none of these is still the case you want solved please let us know so that we can better help you.如果这些都不是您想要解决的情况,请告诉我们,以便我们更好地帮助您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM