ios - Swift ios 如何获取解析的数据并将其分配给标签

标签 ios swift

我想知道如何快速从解析的 json 响应中获取每个名称。我想根据我的代码 cell.label.text = item.name 将响应的名称值分配给 cell.label.text。标签将根据 item.name 的数量自动执行,我想要的是它会根据 json 响应中有多少名称自动执行

 if indexPath.row == 0 {
     // get a reference to our storyboard cell
     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AddNewCell", for: indexPath as IndexPath) as! AddNewCollectionViewCell
     cell.backgroundColor = unselectedCellColor // make cell more visible in our example project
     return cell
 } else {

     let index = IndexPath(row: (indexPath.row - 1), section: 0)

     let item = fetchedResultsController.object(at: index)

     // get a reference to our storyboard cell
     let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! GroceryItemCollectionViewCell
     cell.buttonDelegate = self
     cell.deleteButton.tag = indexPath.row - 1

     cell.label.text = item.name
     if item.isSelected {
          cell.backgroundColor = selectedCellColor
     } else {
          cell.backgroundColor = unselectedCellColor
     }
     return cell
}

HTTP请求代码:

responseString = Optional("[{\"id\":51,\"name\":\"jelord\",\"desc\":\"ako si jelord\",\"reward\":\"1.00\",\"sched\":\"2018-04-06T11:37:09+08:00\",\"parent\":null,\"child\":null,\"occurrence\":{\"name\":\"once\"},\"status\":\"created\"},{\"id\":53,\"name\":\"uuuuuu\",\"desc\":\"uuuuu\",\"reward\":\"8.00\",\"sched\":\"2018-03-06T10:49:54+08:00\",\"parent\":null,\"child\":null,\"occurrence\":{\"name\":\"once\"},\"status\":\"created\"},{\"id\":54,\"name\":\"iiiii\",\"desc\":\"oiii\",\"reward\":\"67.00\",\"sched\":\"2018-02-06T10:51:34+08:00\",\"parent\":null,\"child\":null,\"occurrence\":{\"name\":\"once\"},\"status\":\"created\"},{\"id\":55,\"name\":\"uuuu\",\"desc\":\"uuuu\",\"reward\":\"8.00\",\"sched\":\"2018-03-06T10:52:55+08:00\",\"parent\":null,\"child\":null,\"occurrence\":{\"name\":\"once\"},\"status\":\"created\"},{\"id\":57,\"name\":\"uuuuuuuu\",\"desc\":\"uuuuuu\",\"reward\":\"8888.00\",\"sched\":\"2018-04-06T11:54:16.431000+08:00\",\"parent\":null,\"child\":null,\"occurrence\":{\"name\":\"once\"},\"status\":\"created\"},{\"id\":61,\"name\":\"hhu\",\"desc\":\"yhh\",\"reward\":\"67.00\",\"sched\":\"2018-02-06T13:45:09+08:00\",\"parent\":null,\"child\":null,\"occurrence\":{\"name\":\"once\"},\"status\":\"created\"},{\"id\":62,\"name\":\"huhu\",\"desc\":\"huu\",\"reward\":\"8.00\",\"sched\":\"2018-04-06T14:46:36.620000+08:00\",\"parent\":null,\"child\":null,\"occurrence\":{\"name\":\"once\"},\"status\":\"created\"}]")


code for getting the request.

var request = URLRequest(url: URL(string: "http://test.test:8000/api/v1/test/")!)

        request.httpMethod = "GET"
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {                                                 // check for fundamental networking error
                print("error=\(String(describing: error))")
                return
            }

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(String(describing: response))")
            }

            let responseString = String(data: data, encoding: .utf8)
            print("responseString = \(String(describing: responseString))")
        }
        task.resume()

最佳答案

import UIKit
import Alamofire



class MenuCollectionViewController: UIViewController, 
UICollectionViewDelegate, UICollectionViewDataSource {

var titleArray = [String]()

@IBOutlet var collectionView: UICollectionView!
@IBAction func signOutButtonIsPressed(_ sender: Any) {
    let appDelegate : AppDelegate = UIApplication.shared.delegate as! AppDelegate
    appDelegate.showLoginScreen()
}
@IBOutlet var signoutButton: UIButton!
var items = [Item]()

override func viewDidLoad() {
    super.viewDidLoad()

    self.signoutButton.layer.cornerRadius = 3.0
    demoApi()
}

override func viewWillAppear(_ animated: Bool) {
     super.viewWillAppear(animated)

    self.navigationController?.navigationBar.isHidden = true
    self.navigationItem.hidesBackButton =  true

}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return titleArray.count
}


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

   let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionCell
    cell.nameLabel.text = titleArray[indexPath.row]
    return cell
}



func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    // handle tap events
    print("You selected cell #\(indexPath.item)!")
}

func demoApi() {
    Alamofire.request("https://jsonplaceholder.typicode.com/posts", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in

        switch(response.result) {
        case .success(_):
            guard let json = response.result.value as! [[String:Any]]? else{ return}
            print("Response \(json)")
            for item in json {

                if let title = item["title"] as? String {
                    self.titleArray.append(title)
                }

                DispatchQueue.main.async {
                    self.collectionView.reloadData()
                }
            }
            break

        case .failure(_):
            print("Error")
            break

        }
    }

}

 }


 class CollectionCell: UICollectionViewCell {

@IBOutlet weak var imgPhoto: UIImageView!
@IBOutlet weak var nameLabel: UILabel!


  }

关于ios - Swift ios 如何获取解析的数据并将其分配给标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49687960/

相关文章:

ios - Sprite Kit 创建倒数计时器问题

ios - iCarousel 数据源问题

ios - 如何根据其中的 UILabel subview 调整 UICollectionView 中的单元格大小

swift - Steam 通过日期参数

ios - 为什么自定义 UITableViewCell 中的 UILabel 没有返回正确的高度?

ios - 设置按钮图像最终也会将单词 "button"添加到图像中;怎么修

ios - 如何在 Objective-C 宏中编写多条指令?

ios - 在 iTunes 上上传构建时捆绑操作系统类型代码无效

swift - 获取当前时间作为字符串 swift 3.0

swift - 在 swift 3 中,我目前正在使用 Location 为我的应用程序做一些事情,我想检查它是否在该过程稍后的某个时刻启用