Xamarin.Forms ScrollView

Download Sample 샘플 다운로드

Xamarin.Forms ScrollView

ScrollView 는 콘텐츠를 스크롤할 수 있는 레이아웃입니다. 클래스는 ScrollView 클래스에서 Layout 파생되며 기본적으로 콘텐츠를 세로로 스크롤합니다. A ScrollView 는 다른 레이아웃일 수 있지만 단일 자식만 가질 수 있습니다.

Warning

ScrollView 개체를 중첩하면 안 됩니다. 또한 ScrollView 개체는 스크롤을 제공하는 다른 컨트롤(예: CollectionView, ListView및 )과 WebView함께 중첩되어서는 안 됩니다.

ScrollView는 다음 속성을 정의합니다.

이러한 속성은 개체에 의해 BindableProperty 지원되며, 속성은 데이터 Content 바인딩의 대상이 될 수 있으며 스타일이 지정될 수 있습니다.

속성은 ContentContentProperty 클래스이므로 ScrollView XAML에서 명시적으로 설정할 필요가 없습니다.

최상의 레이아웃 성능을 얻으려면 레이아웃 성능 최적화의 지침을 따르세요.

Root 레이아웃으로 ScrollView

A ScrollView 는 다른 레이아웃일 수 있는 단일 자식만 가질 수 있습니다. 따라서 페이지의 루트 레이아웃이 ScrollView 되는 것이 일반적입니다. 자식 콘텐츠를 ScrollView 스크롤하려면 콘텐츠의 높이와 자체 높이의 차이를 계산합니다. 그 차이는 콘텐츠를 스크롤할 ScrollView 수 있는 양입니다.

A StackLayout 는 종종 의 자식이 ScrollView될 것입니다. 이 시나리오 ScrollViewStackLayout 에서는 자식의 높이 합계만큼 키가 커지게 됩니다. ScrollView 그런 다음 콘텐츠를 스크롤할 수 있는 양을 결정할 수 있습니다. StackLayout에 대한 자세한 내용은 Xamarin.Forms StackLayout을 참조하세요.

주의

ScrollView로로 속성을 < Centera0/&VerticalOptionsA로 설정하지 End않도록 합니다Start. 이렇게 ScrollView 하면 0일 수 있는 키가 필요한 만큼만 키가 커야 합니다. 이러한 사태로부터 보호하지만 Xamarin.Forms , 원하지 않는 것을 제안하는 코드를 피하는 것이 가장 좋습니다.

다음 XAML 예제에는 ScrollView 페이지에 루트 레이아웃이 있습니다.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:ScrollViewDemos"
             x:Class="ScrollViewDemos.Views.ColorListPage"
             Title="ScrollView demo">
    <ScrollView>
        <StackLayout BindableLayout.ItemsSource="{x:Static local:NamedColor.All}">
            <BindableLayout.ItemTemplate>
                <DataTemplate>
                    <StackLayout Orientation="Horizontal">
                        <BoxView Color="{Binding Color}"
                                 HeightRequest="32"
                                 WidthRequest="32"
                                 VerticalOptions="Center" />
                        <Label Text="{Binding FriendlyName}"
                               FontSize="24"
                               VerticalOptions="Center" />
                    </StackLayout>
                </DataTemplate>
            </BindableLayout.ItemTemplate>
        </StackLayout>
    </ScrollView>
</ContentPage>

이 예제 ScrollView 에서는 바인딩 가능한 레이아웃을 StackLayout 사용하여 정의한 필드를 Xamarin.Forms표시하는 콘텐츠 집합이 Color 있습니다. 기본적으로 세로로 ScrollView 스크롤하면 더 많은 콘텐츠가 표시됩니다.

Screenshot of a root ScrollView layout

해당하는 C# 코드는 다음과 같습니다.

public class ColorListPageCode : ContentPage
{
    public ColorListPageCode()
    {
        DataTemplate dataTemplate = new DataTemplate(() =>
        {
            BoxView boxView = new BoxView
            {
                HeightRequest = 32,
                WidthRequest = 32,
                VerticalOptions = LayoutOptions.Center
            };
            boxView.SetBinding(BoxView.ColorProperty, "Color");

            Label label = new Label
            {
                FontSize = 24,
                VerticalOptions = LayoutOptions.Center
            };
            label.SetBinding(Label.TextProperty, "FriendlyName");

            StackLayout horizontalStackLayout = new StackLayout
            {
                Orientation = StackOrientation.Horizontal,
                Children = { boxView, label }
            };
            return horizontalStackLayout;
        });

        StackLayout stackLayout = new StackLayout();
        BindableLayout.SetItemsSource(stackLayout, NamedColor.All);
        BindableLayout.SetItemTemplate(stackLayout, dataTemplate);

        ScrollView scrollView = new ScrollView { Content = stackLayout };

        Title = "ScrollView demo";
        Content = scrollView;
    }
}

바인딩 가능한 레이아웃에 대한 자세한 내용은 에서 바인딩 가능한 레이아웃을 참조 하세요 Xamarin.Forms.

ScrollView를 자식 레이아웃으로

A ScrollView 는 다른 부모 레이아웃에 대한 자식 레이아웃일 수 있습니다.

A ScrollView 는 종종 의 자식이 StackLayout될 것입니다. 콘텐츠 ScrollView 의 높이와 자체 높이의 차이를 계산하려면 특정 높이가 필요하며, 그 차이는 콘텐츠를 스크롤할 수 있는 ScrollView 양입니다. a가 ScrollView 자식인 StackLayout경우 특정 높이를 받지 않습니다. StackLayout 콘텐츠의 ScrollView 높이 ScrollView 또는 0인 최대한 짧기를 원합니다. 이 시나리오를 처리하려면 해당 VerticalOptions 속성을 ScrollView .로 설정 FillAndExpand해야 합니다. 이렇게 하면 StackLayout 다른 자식 ScrollView 이 필요하지 않은 모든 추가 공간을 제공하고 ScrollView 특정 높이를 갖게 됩니다.

다음 XAML 예제에는 다음과 ScrollView 같은 자식 레이아웃이 있습니다.StackLayout

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="ScrollViewDemos.Views.BlackCatPage"
             Title="ScrollView as a child layout demo">
    <StackLayout Margin="20">
        <Label Text="THE BLACK CAT by Edgar Allan Poe"
               FontSize="Medium"
               FontAttributes="Bold"
               HorizontalOptions="Center" />
        <ScrollView VerticalOptions="FillAndExpand">
            <StackLayout>
                <Label Text="FOR the most wild, yet most homely narrative which I am about to pen, I neither expect nor solicit belief. Mad indeed would I be to expect it, in a case where my very senses reject their own evidence. Yet, mad am I not -- and very surely do I not dream. But to-morrow I die, and to-day I would unburthen my soul. My immediate purpose is to place before the world, plainly, succinctly, and without comment, a series of mere household events. In their consequences, these events have terrified -- have tortured -- have destroyed me. Yet I will not attempt to expound them. To me, they have presented little but Horror -- to many they will seem less terrible than barroques. Hereafter, perhaps, some intellect may be found which will reduce my phantasm to the common-place -- some intellect more calm, more logical, and far less excitable than my own, which will perceive, in the circumstances I detail with awe, nothing more than an ordinary succession of very natural causes and effects." />
                <!-- More Label objects go here -->
            </StackLayout>
        </ScrollView>
    </StackLayout>
</ContentPage>

이 예제에는 두 StackLayout 개의 개체가 있습니다. 첫 StackLayout 번째는 개체와 자식 개체가 Label 있는 루트 레이아웃 개체입니다 ScrollView . 이 ScrollView 콘텐츠에는 StackLayout 여러 Label 개체가 포함된 콘텐츠가 StackLayout 있습니다. 이렇게 정렬하면 첫 번째 Label 개체가 항상 화면에 표시되고 다른 Label 개체가 표시하는 텍스트를 스크롤할 수 있습니다.

Screenshot of a child ScrollView layout

해당하는 C# 코드는 다음과 같습니다.

public class BlackCatPageCS : ContentPage
{
    public BlackCatPageCS()
    {
        Label titleLabel = new Label
        {
            Text = "THE BLACK CAT by Edgar Allan Poe",
            // More properties set here to define the Label appearance
        };

        ScrollView scrollView = new ScrollView
        {
            VerticalOptions = LayoutOptions.FillAndExpand,
            Content = new StackLayout
            {
                Children =
                {
                    new Label
                    {
                        Text = "FOR the most wild, yet most homely narrative which I am about to pen, I neither expect nor solicit belief. Mad indeed would I be to expect it, in a case where my very senses reject their own evidence. Yet, mad am I not -- and very surely do I not dream. But to-morrow I die, and to-day I would unburthen my soul. My immediate purpose is to place before the world, plainly, succinctly, and without comment, a series of mere household events. In their consequences, these events have terrified -- have tortured -- have destroyed me. Yet I will not attempt to expound them. To me, they have presented little but Horror -- to many they will seem less terrible than barroques. Hereafter, perhaps, some intellect may be found which will reduce my phantasm to the common-place -- some intellect more calm, more logical, and far less excitable than my own, which will perceive, in the circumstances I detail with awe, nothing more than an ordinary succession of very natural causes and effects.",
                    },
                    // More Label objects go here
                }
            }
        };

        Title = "ScrollView as a child layout demo";
        Content = new StackLayout
        {
            Margin = new Thickness(20),
            Children = { titleLabel, scrollView }
        };
    }
}

Orientation

ScrollViewOrientation 스크롤 방향을 나타내는 속성이 있습니다 ScrollView. 이 속성은 다음 멤버를 정의하는 형식 ScrollOrientation입니다.

  • Vertical 는 세로로 ScrollView 스크롤할 것임을 나타냅니다. 이 멤버는 속성의 기본값입니다 Orientation .
  • Horizontal 는 가로로 ScrollView 스크롤할 것임을 나타냅니다.
  • BothScrollView 가로 및 세로로 스크롤됩니다.
  • NeitherScrollView 스크롤되지 않음을 나타냅니다.

속성을 Neither.로 설정하여 스크롤을 Orientation 사용하지 않도록 설정할 수 있습니다.

스크롤 감지

ScrollViewScrolled 스크롤이 발생했음을 나타내기 위해 발생하는 이벤트를 정의합니다. ScrolledEventArgs 이벤트와 함께 Scrolled 제공되는 개체에는 ScrollXScrollY 두 가지 형식double의 속성이 있습니다.

Important

및 속성은 ScrolledEventArgs.ScrollX 다시 시작 화면으로 스크롤할 때 발생하는 바운스 효과로 인해 음수 값을 가질 수 있습니다ScrollView.ScrolledEventArgs.ScrollY

다음 XAML 예제에서는 이벤트에 대한 Scrolled 이벤트 처리기를 설정하는 방법을 보여줍니다ScrollView.

<ScrollView Scrolled="OnScrollViewScrolled">
		...
</ScrollView>

해당하는 C# 코드는 다음과 같습니다.

ScrollView scrollView = new ScrollView();
scrollView.Scrolled += OnScrollViewScrolled;

이 예제에서는 OnScrollViewScrolled 이벤트가 발생할 때 Scrolled 이벤트 처리기가 실행됩니다.

void OnScrollViewScrolled(object sender, ScrolledEventArgs e)
{
    Console.WriteLine($"ScrollX: {e.ScrollX}, ScrollY: {e.ScrollY}");
}

이 예제 OnScrollViewScrolled 에서 이벤트 처리기는 이벤트와 함께 개체의 ScrolledEventArgs 값을 출력합니다.

참고 항목

Scrolled 이벤트는 사용자가 시작한 스크롤 및 프로그래밍 방식 스크롤에 대해 발생합니다.

프로그래밍 방식으로 스크롤

ScrollView 는 비동기적으로 스크롤하는 두 가지 ScrollToAsync 메서드를 정의합니다 ScrollView. 오버로드 중 하나는 지정된 위치 ScrollView로 스크롤되고 다른 하나는 지정된 요소를 보기로 스크롤합니다. 두 오버로드 모두 스크롤에 애니메이션 효과를 주는지 여부를 나타내는 데 사용할 수 있는 추가 인수가 있습니다.

Important

속성이 ScrollToAsync .로 설정Neither되면 메서드가 ScrollView.Orientation 스크롤되지 않습니다.

보기로 위치 스크롤

인수를 수락하고 인수하는 ScrollView 메서드를 사용하여 ScrollToAsync 한 위치로 스크롤할 수 있습니다doublex.y 이름이 세 ScrollViewscrollView로 개체인 경우 다음 예제에서는 위쪽 ScrollView에서 150개의 디바이스 독립적 단위로 스크롤하는 방법을 보여 주었습니다.

await scrollView.ScrollToAsync(0, 150, true);

세 번째 인수는 animated 프로그래밍 방식으로 스크롤할 때 스크롤 애니메이션이 표시되는지 여부를 결정하는 인수 ScrollToAsync 입니다ScrollView.

요소를 보기로 스크롤

인수 및 수락 메서드를 ScrollView 사용하여 요소 내의 ScrollToAsync 요소를 보기로 스크롤할 수 있습니다Element.ScrollToPosition 명명된 세 ScrollViewLabel 와 이름이 scrollViewlabel지정된 경우 다음 예제에서는 요소를 보기로 스크롤하는 방법을 보여 주었습니다.

await scrollView.ScrollToAsync(label, ScrollToPosition.End, true);

세 번째 인수는 animated 프로그래밍 방식으로 스크롤할 때 스크롤 애니메이션이 표시되는지 여부를 결정하는 인수 ScrollToAsync 입니다ScrollView.

요소를 보기로 스크롤할 때 스크롤이 완료된 후 요소의 정확한 위치를 메서드의 ScrollToAsync 두 번째 인수position로 설정할 수 있습니다. 이 인수는 열거형 멤버를 ScrollToPosition 허용합니다.

  • MakeVisible 는 요소가 에 표시될 때까지 스크롤되어야 했음을 ScrollView나타냅니다.
  • Start 는 요소가 .의 시작 부분까지 스크롤되어야 했음을 ScrollView나타냅니다.
  • Center 는 요소가 .의 가운데로 스크롤되어야 했음을 ScrollView나타냅니다.
  • End 는 요소가 .의 끝으로 스크롤되어야 했음을 ScrollView나타냅니다.

스크롤 막대 표시 유형

ScrollView 바인딩 가능한 속성에 HorizontalScrollBarVisibility 의해 지원되는 정의 및 VerticalScrollBarVisibility 속성입니다. 이러한 속성은 가로 또는 세로 ScrollBarVisibility 스크롤 막대가 표시되는지 여부를 나타내는 열거형 값을 얻거나 설정합니다. ScrollBarVisibility 열거형은 다음 멤버를 정의합니다.

  • Default 는 플랫폼에 대한 기본 스크롤 막대 동작을 나타내며, 및 속성의 HorizontalScrollBarVisibilityVerticalScrollBarVisibility 기본값입니다.
  • Always 은 콘텐츠가 보기에 맞는 경우에도 스크롤 막대가 표시될 것임을 나타냅니다.
  • Never 는 내용이 보기에 맞지 않더라도 스크롤 막대가 표시되지 않음을 나타냅니다.