2017-09-18 1 views
0

Ich bin ein Neuling mit swift und UITableView, ich bekomme Daten von einer Anfrage und ich versuche, das Ergebnis in einer Tabellenansicht anzuzeigen. Ich bekomme Daten sehr gut, aber meine Tabellenansicht scrollt nicht. Ich weiß, dass es viele Probleme mit diesem Problem ist, aber ich sehe andere Antworten, und ich kann nicht von mir lösen dort die Dummy-Code ist:UiTableView cellForRowAt nicht guten Wert und kann nicht scrollen

@IBOutlet weak var tav: UITableView! 
//Emoji array dynamically created 
var emojisArray: [Emoji] = [] 
{ 
    didSet { 
     tav.reloadData() 
    } 
} 
override func viewDidLoad() { 
    super.viewDidLoad() 

    tav.dataSource = self; 
    tav.delegate = self; 


    //backgroundColor 
    self.view.backgroundColor = UIColor(red: 187, green: 222/255, blue: 251, alpha: 1) 
    //Url request 
    let url = "http://localhost:8888/emoji-api/web/app_dev.php/emojis" 
    let request = NSMutableURLRequest(url: URL(string: url)!) 
    request.httpMethod = "GET" 

    let requestAPI = URLSession.shared.dataTask(with: request as URLRequest) {data, response, error in 
     if (error != nil) { 
      print(error!.localizedDescription) // On indique dans la console ou est le problème dans la requête 
     } 
     if let httpStatus = response as? HTTPURLResponse , httpStatus.statusCode != 200 { 
      print("statusCode devrait être de 200, mais il est de \(httpStatus.statusCode)") 
      print("réponse = \(String(describing: response))") // On affiche dans la console si le serveur ne nous renvoit pas un code de 200 qui est le code normal 
     } 
     // let responseAPI = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) 
     //print("responseString = \(String(describing: responseAPI))") // Affiche dans la console la réponse de l'API 
     if error == nil { 
      // Ce que vous voulez faire. 
      DispatchQueue.main.async { 
      do { 

       // let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) 
       if let parsedData = try JSONSerialization.jsonObject(with: data!) as? [[String:Any]]{ 

        for item in parsedData { 

         let emoji = Emoji() 

         //Transform unicode on an Emoji 
         let strUnicodeEmoji = String(UnicodeScalar(Int(item["unicode"] as! String, radix: 16)!)!) 

         print(strUnicodeEmoji) 
         emoji.emojiString = strUnicodeEmoji as String; 
         emoji.description = item["description"] as! String; 

         self.emojisArray.append(emoji) 

        } 
       } 
      } 
      catch { 
        print("Could not serialise") 
       } 
      } 
     } 

    } 
    requestAPI.resume() 
} 

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 

    return emojisArray.count; 
} 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = UITableViewCell(); 
print(emojisArray.count) 
    let emoji = emojisArray[indexPath.row]; 
    cell.textLabel?.text = emoji.emojiString; 

    return cell; 
} 
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
let defVC = segue.destination as! 
    SecondViewController; 
    defVC.emojiSelect = sender as! Emoji 

} 

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    let emojiSelect = emojisArray[indexPath.row]; 

    performSegue(withIdentifier: "secondScreen", sender: emojiSelect) 
} 

ScrollView by default

ich nicht ändern Scrollstandardwert. Vielen Dank

+1

Aufruf 'tableView.reloadData registrieren müssen() 'in Ihrem Abschluss-Block in Ihrem Netzwerk-Anruf nach dem Anhängen' self.emojisArray' – NSGangster

+2

Dies ist Swift. Beseitigen Sie alle diese Semikolons. Und bitte suchen Sie nach Tabellenansichten. Ihr Code zum Erstellen einer Zelle in 'CellForRowAt' ist falsch.Suche auf 'dequeueReusableCell' – rmaddy

+0

Es ist ein Reflex kommen andere Sprachen –

Antwort

1

Below-Code ist ein Performance-Einbußen, Du Nachladen tatsächlich UITableView auf jedes Element auf Ihrem emojisArray hinzugefügt wird.

var emojisArray: [Emoji] = [] 
{ 
    didSet { 
     tav.reloadData() 
    } 
} 

oben Code ersetzen mit diesem

var emojisArray : [Emoji] = [Emoji]() 

einmal neu laden Ihre UITableView, wenn Sie Ihre Datenquelle für zB bereit.

 do { 

      // let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) 
      if let parsedData = try JSONSerialization.jsonObject(with: data!) as? [[String:Any]]{ 
      //Creating temporary array for parsing content 
       var tempArr = [Emoji]() 
       for item in parsedData { 

        let emoji = Emoji() 
        //Your parsing code 
        tempArr.append(emoji) 

       } 

       // Reloading of datasource and UITableView will be done in main thread. 
       DispatchQueue.main.async {          

        self.emojisArray = tempArr 
        //Reloading tableView once all parsing is complete       
        tav.reloadData() 
       } 
      } 

Ihre Tableview UITableViewCell für eine bessere Speichernutzung wiederverwenden müssen, stattdessen jedes Mal eine neue Zelle zuweisen. unten Code cellForRow Methode ersetzen

let cell = UITableViewCell(); 

mit

let cell = tableView.dequeueReusableCell(withIdentifier: "Your_Reusable_Cell_Identifier", for: indexPath) as! Your_CustomTableViewCell 

Hinweis: wiederverwendbar Benutzerdefinierte UITableViewCell So verwenden Sie Ihr Handy mit Ihrem UITableView Siehe "UITableView - registerClass with Swift"

+0

Vielen Dank für Ihre Antwort, aber ich weiß nicht, wo kann ich" Your_CustomTableViewCell "finden/definieren? –

+0

Hey bitte gehen Sie durch diese https://www.ralfebert.de/tutorials/ios-swift-uitableviewcontroller/custom-cells/, um Ihre eigene benutzerdefinierte TableViewCell –

+0

Vielen Dank jetzt es funktioniert, ich folgte Ihren Ratschlägen und Thesen zwei Tutorials: https://www.ralfebert.de/tutorials/ios-swift-uitableviewcontroller/custom-cells/ und https://developer.apple.com/library/content/referencelibrary/GettingStarted/DevelopiOSAppsSwift/CreateATableView.html. Endgültiger Code http://swift.sandbox.bluemix.net/#/repl/59c0f56588c199772ebcd59a –

0

Es sieht so aus, als würden Sie Ihre Zellen nicht abstellen. Weitere Informationen finden Sie in den Dokumenten zur Wiederverwendung von Zellen.

let cell = UITableViewCell(); 

Sollte

let cell = tableView.dequeueReusableCell(withIdentifier: "YOUR_CELL_IDENTIFIER", for: indexPath) 

sein Wenn Sie Storyboards verwenden Sie die Cell-Identifier im Identity Inspector unter die Zelle gesetzt haben.

Hoffe, das hilft.

1

Überprüfen Sie, Ihre UITableView hat Datenquelle und Delegate Verbindung.

Dequeue Zelle

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "YOUR_CELL_IDENTIFIER", for: indexPath) as! Your_tableview_cell 

    let emoji = emojisArray[indexPath.row]; 
    cell.textLabel?.text = emoji.emojiString;   

    return cell 
} 

Reload Tabellenansicht

DispatchQueue.main.async { 
     do { 

      let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) 
      if let parsedData = try JSONSerialization.jsonObject(with: data!) as? [[String:Any]]{ 

       for item in parsedData { 

        ... // your code 
        ... 

       } 

       YOUR_TABLEVIEW.reloadData(); // You have to reload ur tableview 
            // in main queue after getting 
            //all values in Array 
      } 
     } 
     catch { 
       print("Could not serialise") 
      } 
     } 
Verwandte Themen