簡體   English   中英

Xamarin Forms ScrollView無法正確滾動

[英]Xamarin Forms ScrollView is not scrolling correctly

我們有一個即時消息應用程序。 我們希望在收到消息時自動滾動,以便顯示新消息。 當前,當收到第一條需要滾動的消息時,頁面不會滾動。 也就是說,新消息隱藏在我們的輸入控件后面。 它需要另一條消息或用戶調整滾動視圖,然后它才能正常工作。

我們的xaml是這樣的:

<ContentPage>
  <StackLayout x:Name="mainStackLayout">
    <customControls:NavBar />
    <ScrollView x:Name="mainScrollView">
      <StackLayout x:Name="mainScrollViewStackLayout">
        <ScrollView x:Name="messagesScrollView">
          <StackLayout x:Name="messagesScrollViewContentStackLayout">
            <!-- Messages are programmatically inserted here -->
          </StackLayout>
        </ScrollView>
      </StackLayout>
    </ScrollView>
    <StackLayout>
      <!-- a couple buttons/inputs for sending messages -->
    </StackLayout>
  </StackLayout>
</ContentPage>

我們調用滾動的代碼如下所示:

public void ScrollMessagesToEnd()
{

    StackLayout messagesContent = (messagesScrollView.Content as StackLayout);
    var frame = messagesContent.Children.LastOrDefault();

    if (frame != null)
    {
            messagesScrollView.ScrollToAsync(frame, ScrollToPosition.MakeVisible, true);
    }
}

無論采用哪種解決方案,都應使ScrollMessagesToEnd異步,並且您需要await ScrollToAsync() 由於您現在正在等待ScrollToAsync() ,因此建議您在UI線程上顯式運行它。

之后,您可以嘗試將await Task.Delay(300)添加到方法的頂部,我之前必須這樣做。

您可能還想嘗試啟用和禁用動畫,我發現它們可以影響滾動效果,但是在每個平台上都要進行測試,因為每個平台上的效果可能會有所不同。

public async Task ScrollMessagesToEndAsync() //Adding Async to method name, also try to return Task and await this method in the calling code as well
{
    await Task.Delay(300); //Sometimes code runs too fast and a delay is needed, you may test whether only a specific platform needs the delay

    StackLayout messagesContent = (messagesScrollView.Content as StackLayout);
    var frame = messagesContent.Children.LastOrDefault();

    if (frame != null)
    {
        Device.BeginInvokeOnMainThread(async () => await messagesScrollView.ScrollToAsync(frame, ScrollToPosition.MakeVisible, true)); //You could try passing in false to disable animation and see if that helps
    }
}

我強烈建議不要使用嵌套的滾動視圖,但是如果保留它們,那么這里就是解決方案。

代替

messagesScrollView.ScrollToAsync(frame, ScrollToPosition.MakeVisible, true);

采用

mainScrollView.ScrollToAsync(frame, ScrollToPosition.End, true);

要么

mainScrollView.ScrollToAsync(frame, ScrollToPosition.MakeVisible, true);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM