Nativescript - 如何正确使用 ui/image-cache 中的占位符 属性 使其正常工作?

Nativescript - How do I properly use placeholder property from ui/image-cache to make it work?

我正在尝试使用一组远程图像创建列表视图,并在加载它们时显示占位符图像。

var imageSource = require("image-source");
var imageCache = require("ui/image-cache");
var cache = new imageCache.Cache();
var defaultImageSource = imageSource.fromResource("img-loading”);

cache.enableDownload();
cache.placeholder = defaultImageSource;
cache.maxRequests = 5;

也尝试使用 fromFile 而不是 fromResource。

有什么问题吗?

我不确定您如何使用 ImageCache,但您不能直接将 ImageCache 对象设置为 Image 的来源。为了实现你想要的,你必须使用这样的东西(取自http://pstaev.blogspot.com/2016/04/using-nativescripts-imagecache-to-cache.html):

主要-page.xml

<Page xmlns="http://schemas.nativescript.org/tns.xsd" 
      navigatingTo="navigatingTo">
    <ListView items="{{ images }}">
      <ListView.itemTemplate>
        <GridLayout>
          <Image src="{{ imageSrc }}" stretch="aspectFill" height="100"/>
        </GridLayout>
      </ListView.itemTemplate>
    </ListView>
</Page>

主要-page.ts

import observableArray = require("data/observable-array");
import observable = require("data/observable");
import imageItem = require("./image-item");
import pages = require("ui/page");

export function navigatingTo(args: pages.NavigatedData)
{
    var page = <pages.Page>args.object;
    var model = new observable.Observable();
    var images = new observableArray.ObservableArray<imageItem.ImageItem>();

    images.push(new imageItem.ImageItem("http://foo.com/bar1.jpg"));
    images.push(new imageItem.ImageItem("http://foo.com/bar2.jpg"));
    // ...
    images.push(new imageItem.ImageItem("http://foo.com/bar100.jpg"));

    model.set("images", images);
    page.bindingContext = model;
}

图片-item.ts

import observable = require("data/observable");
import imageCache = require("ui/image-cache");
import imageSource = require("image-source");

var cache = new imageCache.Cache();
cache.maxRequests = 10;
cache.placeholder = imageSource.fromResource("img-loading")

export class ImageItem extends observable.Observable
{
    private _imageSrc: string
    get imageSrc(): imageSource.ImageSource
    {
        var image = cache.get(this._imageSrc); 

        if (image)
        {
            return image;
        }

        cache.push(
            {
                key: this._imageSrc
                , url: this._imageSrc
                , completed:
                (image) =>
                {
                    this.notify(
                        {
                            object: this
                            , eventName: observable.Observable.propertyChangeEvent
                            , propertyName: "imageSrc"
                            , value: image
                        });
                }
            });

        return cache.placeholder;
    }

    constructor(imageSrc : string)
    {
        super();
        this._imageSrc = imageSrc;
    }
}