问题
I'm trying to create a list view with a set of remote images and while they are loading to display a placeholder image.
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;
Tried with fromFile as well instead of fromResource.
Any toughts?
回答1:
I'm not sure how are you using the ImageCache but you cannot directly set an ImageCache object as source of an Image. In order to achieve what you want you must use something like this (taken from http://pstaev.blogspot.com/2016/04/using-nativescripts-imagecache-to-cache.html):
main-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>
main-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;
}
image-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;
}
}
来源:https://stackoverflow.com/questions/36072301/nativescript-how-do-i-properly-use-placeholder-property-from-ui-image-cache-to