Reputation: 1870
Here is the code that I tried, but when the image has not loaded yet, nothing show up (an animated indicator should show up). What is the best practice of showing the activity indicator? I hooked into the ASNetworkImageNodeDelegate.
import AsyncDisplayKit
class WideImageFeedNode : ASCellNode, ASNetworkImageNodeDelegate {
var imageNode = ASNetworkImageNode()
var activityIndicator:UIActivityIndicatorView?
init(itemid:Int) {
super.init()
imageNode.backgroundColor = ASDisplayNodeDefaultPlaceholderColor()
let imgURL = URL(string:"http://...somelargeimage.jpg")
imageNode.url = imgURL
imageNode.delegate = self
self.addSubnode(imageNode)
self.automaticallyManagesSubnodes = true
}
override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
var finalStackArr:[ASLayoutElement] = [self.imageNode]
let finalSpec = ASStackLayoutSpec(direction: .vertical, spacing: 10.0, justifyContent: .start, alignItems: .start, children: finalStackArr)
return finalSpec
}
func imageNode(_ imageNode: ASNetworkImageNode, didLoad image: UIImage) {
if let activityIndicator = self.activityIndicator {
activityIndicator.removeFromSuperview()
self.activityIndicator = nil
}
self.setNeedsLayout()
}
// helper functions
func setupActivityIndicator(bounds:CGSize) -> UIActivityIndicatorView {
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
var refreshRect = activityIndicator.frame
refreshRect.origin = CGPoint(x: (bounds.width - activityIndicator.frame.size.width) / 2.0, y: (bounds.height - activityIndicator.frame.size.height) / 2.0)
activityIndicator.frame = refreshRect
return activityIndicator
}
func imageNodeDidStartFetchingData(_ imageNode: ASNetworkImageNode) {
self.activityIndicator = setupActivityIndicator(bounds: imageNode.style.preferredSize)
imageNode.view.addSubview(self.activityIndicator!)
}
func imageNode(_ imageNode: ASNetworkImageNode, didFailWithError error: Error) {
if let activityIndicator = self.activityIndicator {
activityIndicator.removeFromSuperview()
self.activityIndicator = nil
}
}
}
Upvotes: 1
Views: 622
Reputation: 1870
Never mind, it works. I was missing one call:
func imageNodeDidStartFetchingData(_ imageNode: ASNetworkImageNode) {
self.activityIndicator = setupActivityIndicator(bounds: imageNode.style.preferredSize)
imageNode.view.addSubview(self.activityIndicator!)
self.activityIndicator!.startAnimating()
}
Upvotes: 1