UiTableView cellForRowAt 不是 return 很好的价值,不能滚动
UiTableView cellForRowAt not return good value and can't scroll
我是 swift 和 UITableView 的新手,我正在从请求中获取数据,并试图在 table 视图中显示结果。
我获取的数据非常好,但我的 table 视图无法滚动。我知道这个问题有很多问题,但我看到其他人的答案,但我无法解决我的问题,因为有伪代码:
@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默认值。
谢谢
您似乎没有让您的单元格出队。有关更多信息,请查看有关重用单元格的文档。
let cell = UITableViewCell();
应该是
let cell = tableView.dequeueReusableCell(withIdentifier: "YOUR_CELL_IDENTIFIER", for: indexPath)
如果您使用的是故事板,则必须在单元格下的身份检查器中设置单元格标识符。
希望对您有所帮助。
检查,您的 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
}
重新加载Table查看
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")
}
}
下面的代码会影响性能,您实际上是在为 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”
我是 swift 和 UITableView 的新手,我正在从请求中获取数据,并试图在 table 视图中显示结果。 我获取的数据非常好,但我的 table 视图无法滚动。我知道这个问题有很多问题,但我看到其他人的答案,但我无法解决我的问题,因为有伪代码:
@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默认值。 谢谢
您似乎没有让您的单元格出队。有关更多信息,请查看有关重用单元格的文档。
let cell = UITableViewCell();
应该是
let cell = tableView.dequeueReusableCell(withIdentifier: "YOUR_CELL_IDENTIFIER", for: indexPath)
如果您使用的是故事板,则必须在单元格下的身份检查器中设置单元格标识符。
希望对您有所帮助。
检查,您的 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
}
重新加载Table查看
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")
}
}
下面的代码会影响性能,您实际上是在为 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”