我正在基本的tableview单元格中加载不同的图像,并希望在加载图像时在单元格中显示活动指示符。我正在使用单独的单元格文件,如示例代码。我知道在哪里放置代码只是不完全确定语法。我发现了一些方法可以将代码放入视图中,但不是特定于单元格中。有人有想法吗?感谢。
func configureCell(favorite: Article) {
self.favorite = favorite
downloadImage(NSURL(string: self.favorite.mainImage)!)
func downloadImage(url: NSURL, type: String) {
getDataFromUrl(url) { (data, response, error) in
//show activity indicator
dispatch_async(dispatch_get_main_queue()) { () -> Void in
guard let data = data where error == nil else { return }
self.mainImage.image = UIImage(data: data)
}
}
}
func getDataFromUrl(url: NSURL, completion: ((data: NSData?, response: NSURLResponse?, error: NSError?) -> Void)) {
NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) in
completion(data: data, response: response, error: error)
}.resume()
}
答案 0 :(得分:2)
你可以在下面这样做,让我知道如果这对你有用,你可以根据你的要求修改frame
。
func downloadImage(url: NSURL, type: String) {
let activityIndicator = UIActivityIndicatorView()
activityIndicator.frame = slef.mainImage.bounds
getDataFromUrl(url) { (data, response, error) in
//show activity indicator
self.mainImage.addSubview(activityIndicator)
activityIndicator.startAnimating()
dispatch_async(dispatch_get_main_queue()) { () -> Void in
guard let data = data where error == nil else { return }
activityIndicator.stopAnimating()
activityIndicator.removeFromSuperview()
self.mainImage.image = UIImage(data: data)
}
}
}