2017-09-18 40 views
0

我是一個swift和UITableView的新手,我從請求中獲取數據,並試圖在表視圖上顯示結果。 我得到的數據非常好,但我的表格視圖不滾動。我知道有這個問題的許多問題,但我看到別人的答案,我解決不了我的存在啞代碼:UiTableView cellForRowAt不返回良好的價值,不能滾動

@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

我不修改滾動視圖默認值。 謝謝

+1

電話'tableView.reloadData註冊您的()'在你的完成塊中添加'self.emojisArray'後你的網絡調用中 – NSGangster

+2

這是Swift。擺脫所有這些分號。並請使用表格視圖進行一些搜索。你在'cellForRowAt'中創建單元格的代碼都是錯誤的。搜索'dequeueReusableCell' – rmaddy

+0

這是來自其他語言的反射 –

回答

1

下面的代碼是一個性能命中,你實際上是重裝每一個元素上的UITableView您emojisArray添加。

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

替換上面的代碼與此

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

刷新您的UITableView一次,當你得到你的數據源準備比如。

 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() 
       } 
      } 

你泰伯維必須重用的UITableViewCell更好的內存利用率,而不是每次分配一個新的小區。 替換下面的代碼cellForRow方法

let cell = UITableViewCell(); 

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

注意:要使用可重複使用的自定義的UITableViewCell您必須使用的UITableView 請參閱 「UITableView - registerClass with Swift

+0

感謝您的回答,但我不知道我在哪裏可以找到/定義「Your_CustomTableViewCell」? –

+0

嘿,請通過這個https://www.ralfebert.de/tutorials/ios-swift-uitableviewcontroller/custom-cells/來創建自己的自定義TableViewCell –

+0

謝謝你現在工作,我遵循你的建議和這兩個教程: https://www.ralfebert.de/tutorials/ios-swift-uitableviewcontroller/custom-cells/和https://developer.apple.com/library/content/referencelibrary/GettingStarted/DevelopiOSAppsSwift/CreateATableView.html。最終代碼http://swift.sandbox.bluemix.net/#/repl/59c0f56588c199772ebcd59a –

0

看起來你並不是在等待你的細胞排隊。有關更多信息,請查看關於重複使用單元格的文檔。

let cell = UITableViewCell(); 

應該

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

如果你使用的故事板,你就必須設置在Identity Inspector中的小區標識你的下。

希望這會有所幫助。

1

檢查,您的UITableView有數據源和委託連接。

出列細胞

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 
} 

刷新表視圖

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") 
      } 
     }