Reputation: 15
I'm quite new to Swift 4, came from Android Studio into Xcode.
I'm having an issue with Collection Views, the thing is if I fill a struct decodable with pre-determined data the cell it's clickable and passes to the didSelectItemat function. But when I'm getting the said data from a JSON from the server it doesn't.
My question is if there anything that it's passing over my head, or if I'm missing something.
Here's the code that I'm using:
struct SelectJogos: Decodable{ let success: Bool let jogos: [Jogos] }
struct Jogos: Decodable{
let NumJogo: Int
let EquipaA: String
let EquipaB: String
let Fase: String
let Serie: String
let CodComp: String
let Data: String
let Hora: String
let Local: String
}
class SubmeteController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var collectionView: UICollectionView!
var jogo = [Jogos]()
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
//User em sessão
let user = UserDefaults.standard.string(forKey: "username")
print(user!)
//MandaPost para o server
let url = URL(string: "http://yourexemple.com/something")
var request = URLRequest(url: url!)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let postString = "clube=\(user!)&opera=select"
request.httpBody = postString.data(using: .windowsCP1252)
//Receve a info do sv
let task = URLSession.shared.dataTask(with: request){data, request, error in
guard let data = data, error == nil else{
print("error=\(error!)")
return
}
do{
let dataServer = try JSONDecoder().decode(SelectJogos.self, from: data)
if dataServer.success != false{
self.jogo = dataServer.jogos
print(dataServer.success)
}else{
print("nogames")
}
DispatchQueue.main.async {
print("Number of Data:\(self.jogo.count)")
self.collectionView.reloadData()
}
}catch let jsonERR{
print("Error DO: ", jsonERR)
}
}
task.resume()
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("clicked")
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return jogo.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "customCell", for: indexPath) as! SubmeteListaViewCell
cell.NumJogo.text = String(jogo[indexPath.row].NumJogo)
print(jogo[indexPath.row].CodComp)
print(indexPath)
return cell
}
}
Upvotes: 0
Views: 52
Reputation: 100503
You have to set the delegate in viewDidLoad
`
collectionView.delegate = self
Upvotes: 2