从 api 获取所有数据以及如何在 swift ios 中仅在单元格上附加标题
Posted
技术标签:
【中文标题】从 api 获取所有数据以及如何在 swift ios 中仅在单元格上附加标题【英文标题】:get all data from an api and how to append only the title on a cell in swift ios 【发布时间】:2018-04-07 07:21:40 【问题描述】:我的代码如下,用于使用 alamofire 从 api 中提取数据。我只拉了“标题”。并附加它。我想要的是如何从 api 获取所有数据,包括 id、body 和所有数据,但只会在单元格上附加名称,我不希望显示所有数据。只有当您选择单元格#(indexPath.item) 时,才会显示数据的详细信息!其详细信息将显示在警报中。我在下面有我的警报代码。例如,我获取了所有数据,但我只显示单元格上的“标题”,当我单击单元格时,它将显示其数据,就像我单击 indexpath 为 1 的标题时,它将显示 id、正文和所有详细信息的那个标题。谢谢。
alert
let alert = UIAlertController(title: "\(titleArray[indexPath.row])", message: "", preferredStyle:
UIAlertControllerStyle.alert)
let subview = (alert.view.subviews.first?.subviews.first?.subviews.first!)! as UIView
subview.backgroundColor = UIColor(red: 93/255, green: 173/255, blue: 195/255, alpha: 1.0)
alert.view.tintColor = UIColor.black
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil))
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: [weak alert] (_) in
// let textField = alert?.textFields![0] // Force unwrapping because we know it exists.
//
// if textField?.text != ""
// print("Text field: \(textField?.text!)")
// self.saveDataInCoreData(nameOfGroccery: (textField?.text)!)
// self.setUpCollectionView()
//
//
// item.isSelected = true
print("oo")
))
self.present(alert, animated: true, completion: nil)
API 示例
“用户ID”:1, “身份证”:1, "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", “body”:“quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto” ,
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!
【问题讨论】:
【参考方案1】:喜欢
第一步
在当前类中创建字典数组
var getAllDetail: [[String:Any]] = [[String:Any]]()
第二步
将您的迭代字典附加到名为 getAllDetail 的新字典数组中
case .success(_):
guard let json = response.result.value as! [[String:Any]]? else return
print("Response \(json)")
for item in json
getAllDetail.append(item)
// if let title = item["title"] as? String
// self.titleArray.append(title)
//
if !getAllDetail.isEmpty
DispatchQueue.main.async
self.collectionView.reloadData()
break
第三步
最后将值附加到您的收藏视图
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
return getAllDetail.count
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionCell
if let getTempDetails: [String : Any] = getAllDetail[indexPath.row]
cell.nameLabel.text = getTempDetails["title"] as? String ?? "" //titleArray[indexPath.row]
return cell
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
// handle tap events
print("You selected cell #\(indexPath.item)!")
if let getTempDetails: [String : Any] = getAllDetail[indexPath.row]
print("You selected ID #\( getTempDetails["userId"] as? String ?? "" )!")
【讨论】:
条件绑定的初始化程序必须具有可选类型,而不是 '[String : Any]' 在行 if let getTempDetails = getAllDetail[indexPath.row] @DurnKurvirck- 更改此if let getTempDetails: [String : Any] = getAllDetail[indexPath.row]
我会实施它先生
“getAllDetail”重新声明无效
哎呀对不起我的错误以上是关于从 api 获取所有数据以及如何在 swift ios 中仅在单元格上附加标题的主要内容,如果未能解决你的问题,请参考以下文章
Swift iOS - 如何在按下单元格之前从 TableView 的所有 IndexPath 中获取数据
Swift - 如何从 mapViewkit 中的 API 数据创建要使用的局部变量
我如何从 struct 获取纬度和经度并在 mapbox Swift 上显示它们