【发布时间】:2014-02-19 22:40:01
【问题描述】:
我在将多个 UIWebView 异步加载到一个部分时遇到问题。我正在使用 MonoTouch.Dialog 来生成 UI。我正在从博客加载数据并显示 10 个项目,其中包括一个图像和一些 HTML 文本。正在发生的事情是帖子并未全部显示,并且显示的帖子出现故障。这就是我正在做的事情:
public partial class BlogViewController : DialogViewController
{
private Section mainSection;
public BlogViewController () : base (UITableViewStyle.Grouped, null)
{
Root = new RootElement ("");
mainSection = new Section ("");
mainSection.Add(new ActivityElement ());
Root.Add (mainSection);
}
public override void ViewDidLoad()
{
base.ViewDidLoad ();
new Thread (new ThreadStart(PopulateBlog)).Start ();
}
private void PopulateBlog ()
{
var posts = service.GetPosts (currentOffset, 10);
InvokeOnMainThread (delegate {
foreach (var post in posts) {
//grab an appropriate image size
var altSize = post.photos [0].alt_sizes.Where (x => x.width < 401).OrderByDescending(x => x.width).FirstOrDefault ();
if (altSize != null) {
var img = LoadImageFromUri(altSize.url);
//scale the image, not really important
var imageView = new UIImageView (new RectangleF (0, 0, screenWidth, height));
imageView.Image = img;
var content = new UIWebView ();
//When the HTML finishes rendering figure out the size and add it to the section. Apparently can't figure the size ahead of time?
content.LoadFinished += (sender, e) =>
{
var contentHeight = Int32.Parse (content.EvaluateJavascript ("document.getElementById('content').offsetHeight;"));
content.Frame = new RectangleF (0, height + 10, screenWidth, contentHeight + 10);
//dynamically size this view to fit the content
var view = new UIView
(new RectangleF (0, 0,
screenWidth,
height + contentHeight));
view.AddSubview (content);
view.AddSubview (imageView);
//add the view to the Section which is later added to the Root
mainSection.Add(view);
};
var htmlString = @"some HTML here";
content.LoadHtmlString(someHtml);
content.ScrollView.ScrollEnabled = false;
content.ScrollView.Bounces = false;
}
}
});
Root.Reload(mainSection, UITableViewRowAnimation.None);
}
}
我猜 A) LoadFinished 事件的发生顺序与它们排队的顺序不同,并且 B) Root.Reload 在它们全部触发之前被调用。我尝试在 Root.Reload 之前使用 Thread.Sleep 旋转,但之后 LoadFinished 事件甚至从未被触发。
我还尝试将所有 UIView 元素放入字典中,以便在它们全部填充后添加,但似乎一旦 InvokeOnMainThread 结束,LoadFinished 事件处理程序就再也不会被调用。
【问题讨论】: