【问题标题】:tableView reloadData cellForRowAtIndexPath not called未调用 tableView reloadData cellForRowAtIndexPath
【发布时间】:2016-03-30 20:59:27
【问题描述】:

我有一个带有 UITableView 的 UITableViewController(当然),我的问题是如何在运行时更新 tableView 中的数据?

因为当我在 viewWillAppear 方法中调用 reloadData 时,它工作得很好,但在后面的代码中它什么也没做。

Number of rows 方法被调用并返回非零数,但 cellForRowAtIndexPath 没有被调用,所以表格没有被更新...

class CropTableViewController: UITableViewController {

var photos = [Photo]()

var photoAssets = [PHAsset]()

override func viewDidLoad() {
    super.viewDidLoad()

    self.automaticallyAdjustsScrollViewInsets = false
}

override func viewWillAppear(animated: Bool) {
    refreshData()
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    print("rows called: \(photos.count)")  // prints non-zero 
    return photos.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    print("cell called")

    let cellIdentifier = "Cell"
    let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! CropTableViewCell

    let photo = photos[indexPath.row]


    cell.photoImageView.image = photo.photo

    return cell
}

func refreshData(){
    if (loadPhotos() != nil){
        photos = loadPhotos()!
        tableView.reloadData()
    }

    print("refreshData called \(photos.count)")
}
}

编辑:

loadPhotos 只是从 iphone 内存中加载图像:

func loadPhotos() -> [Photo]? {
    return NSKeyedUnarchiver.unarchiveObjectWithFile(Photo.ArchiveURL.path!) as? [Photo]
}

在这个循环中从另一个类调用refreshData:

for asset in photoAssets {
        let manager: PHImageManager = PHImageManager.defaultManager()
        let scale: CGFloat = UIScreen.mainScreen().scale
        let targetSize: CGSize = CGSizeMake(300.0 * scale, 180.0 * scale)

        manager.requestImageForAsset(asset, targetSize: targetSize, contentMode: .AspectFill, options: self.requestOptions, resultHandler: {(image, info) -> Void in
            let photo = Photo(photo: image!)
            self.photos.append(photo!)
            print("photos count \(self.photos.count)")
            self.savePhotos()
            CropTableViewController().refreshData()
        })
    }

【问题讨论】:

  • loadPhotos做了什么?是异步的吗?您在refreshData 中的代码应该获得loadPhotos() 的值并检查它是否为非零,而不是调用该函数两次。你能说明你是如何调用refreshData“稍后在代码中”的吗?
  • 我已经编辑了问题。

标签: ios arrays swift uitableview


【解决方案1】:

在黑暗中拍摄。试试这个:

func refreshData(){
    if let photos = loadPhotos() {
        dispatch_async(dispatch_get_main_queue())
        {
            photos = photos
            tableView.reloadData()
        }  
    }

    print("refreshData called \(photos.count)")
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    • 1970-01-01
    • 1970-01-01
    • 2014-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多