数据从 Web API 获取,并应填充表格 View 。
问题:获取数据后,tableView 会填充大部分数据,但除非滚动 tableView,否则单元格中的某些数据不会显示。一旦将 tableView 滚动回该单元格,数据就会开始显示。
这是我的代码。
属性:
var upcomingPrograms: [SabaCenterData.UpcomingProgram] = [] {
didSet {
self.stopActivityIndicator()
self.tableView.reloadData()
}
}
var imageCache = [URL : UIImageView]()
查看周期和助手:
override func viewDidLoad() {
super.viewDidLoad()
self.fetchUpcomingPrograms()
}
func fetchUpcomingPrograms() {
showActivityIndicator()
GoogleDocsClient.shared().getUpcomingPrograms {
(data, error) in
if let data = data {
self.upcomingPrograms = data
} else {
// FIXME: ERROR HANDLING!
}
}
}
表格 View :
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "upcomingProgramCell", for: indexPath) as! UpcomingProgramsCell
let upcomingProgram = upcomingPrograms[indexPath.row]
cell.upcomingProgramTextView.attributedText = makeAttributedString(title: upcomingProgram.title, subtitle: upcomingProgram.description)
cell.accessoryView = UIImageView(image: #imageLiteral(resourceName: "PlaceHolder"))
if let imageurl = URL(string: upcomingProgram.imageURL!) {
if let img = imageCache[imageurl] {
cell.accessoryView = img
} else {
if let data = try? Data(contentsOf: imageurl) {
if let image = UIImage(data: data) {
let imgView = UIImageView(image: image)
imgView.frame = CGRect(x: 0.0, y: 0.0, width: 100.0, height: 110.0)
imgView.layer.cornerRadius = 8.0
imgView.contentMode = .scaleAspectFit
imageCache[imageurl] = imgView
performUIUpdatesOnMain {
cell.accessoryView = imgView
}
}
}
}
}
return cell
}
编辑:tableView 填充了数据,但有些数据在我上下滚动之前不会显示所有数据!
也许是因为这两个函数?
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
我根据内容动态调整单元格的高度。该单元格还有一个 textView(如果这有助于澄清情况......)。
编辑 2:我在此处上传了整个项目 -> https://github.com/alimir1/Saba-Center
最佳答案
听起来你需要在某个地方调用 tableView.reloadData() 。
当您滚动时,它会自动调用 cellForRowAtIndexPath:
,因为它会释放单元格以供稍后重用。但听起来您并没有同时拥有所有数据。调用 tableView.reloadData() 将为您填充所有内容,但您没有提供足够的代码来了解具体位置。也许在 self.upcomingPrograms = data
之后?
没有更多信息,这就是您能得到的最好的信息。
关于ios - 一些 uitableviewcell 在我滚动 iPhone 之前不会显示所有数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40642609/