如何显示ASNetworkImageNode的活动指示器?

时间:2017-04-21 23:23:40

标签: swift uiactivityindicatorview asyncdisplaykit

这是我尝试的代码,但是当图像尚未加载时,什么都没有显示(应该显示动画指示)。显示活动指标的最佳做法是什么?我迷上了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
        }
    }



}

1 个答案:

答案 0 :(得分:0)

没关系,它有效。我错过了一个电话:

func imageNodeDidStartFetchingData(_ imageNode: ASNetworkImageNode) {
    self.activityIndicator = setupActivityIndicator(bounds: imageNode.style.preferredSize)
    imageNode.view.addSubview(self.activityIndicator!)
    self.activityIndicator!.startAnimating()
}