gpt4 book ai didi

ios - UiTableView cellForRowAt 没有返回好的值并且无法滚动

转载 作者:行者123 更新时间:2023-11-28 12:16:44 24 4
gpt4 key购买 nike

我是 swift 和 UITableView 的新手,我正在从请求中获取数据,并试图在表格 View 上显示结果。我得到的数据很好,但我的表格 View 不滚动。我知道这个问题有很多问题,但我看到其他人的答案,但我无法解决我的问题,因为有伪代码:

 @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

我不修改 scrollview 默认值。谢谢

最佳答案

下面的代码会影响性能,您实际上是在为 emojisArray 添加的每个元素重新加载 UITableView。

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

您的 Tableview 必须重用 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

关于ios - UiTableView cellForRowAt 没有返回好的值并且无法滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46289232/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com