我有下面的代码,用于使用alamofire从api中提取数据。我只是拉了#34;标题" 。并追加它。我想要的是如何从api获取所有数据,包括id,body和all,但只会在单元格上附加名称,我不希望显示所有数据。只有当您选择了单元格#(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样本
{ " userId":1, " id":1, " title":" sunt autrerere 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!
}
答案 0 :(得分:1)
喜欢
<强>步骤1 强>
在当前类中创建字典数组
var getAllDetail: [[String:Any]] = [[String:Any]]()
<强>步骤-2 强>
将您的iterate dict附加到名为getAllDetail的新Dict数组
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
<强>步骤-3 强>
最后将该值附加到您的集合视图
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 ?? "" )!")
}
}