我有一个带UITableView的UITableViewController(当然),我的问题是如何在运行时更新tableView中的数据?
因为当我在viewWillAppear方法中调用reloadData时,它可以很好地工作,但是后来在代码中它什么都不做。
调用行数方法并返回非零数字,但不调用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()
})
}
答案 0 :(得分:0)
在黑暗中拍摄。试试这个:
func refreshData(){
if let photos = loadPhotos() {
dispatch_async(dispatch_get_main_queue())
{
photos = photos
tableView.reloadData()
}
}
print("refreshData called \(photos.count)")
}