Xamarin.Forms Custom Slider With Floating Text

Tuğçe Arar
2 min readAug 11, 2018

--

The topic of this article is to place a floating text on the slider icon as it moves, without having to define a custom renderer. You can download the project here.

First, we define our page:

<StackLayout VerticalOptions="Center">
<Label x:Name="lblText" Text="0" HorizontalOptions="Start" FontSize="Micro" HorizontalTextAlignment="Center" VerticalOptions="EndAndExpand">
<Label.Margin>
<OnPlatform x:TypeArguments="Thickness">
<On Platform="iOS" Value="15,0" />
<On Platform="Android" Value="10,0" />
</OnPlatform>
</Label.Margin>
</Label>
<Slider x:Name="mySlider" Maximum="10000" Minimum="100" HorizontalOptions="FillAndExpand"
ValueChanged="Slider_ValueChanged" >
<Slider.Margin>
<OnPlatform x:TypeArguments="Thickness">
<On Platform="iOS" Value="10,0" />
</OnPlatform>
</Slider.Margin>
</Slider>
</StackLayout>

Then, we write the code that when the slider icon moves, the text above it move and change with it.

void Slider_ValueChanged(object sender, Xamarin.Forms.ValueChangedEventArgs e)
{
var newStep = Math.Round(e.NewValue / 100); mySlider.Value = newStep * 100; lblText.Text = mySlider.Value.ToString(); lblText.TranslateTo(mySlider.Value * ((mySlider.Width - 40) / mySlider.Maximum) , 0, 100);
}

I’m explain the TranslateTo method we used here. This method is one of the extension methods provided by the ViewExtension class. Other than TranslateTo, this class also includes RelScaleTo, RotateTo, RelRotateTo, RotateXTo, RotateYTo and FadeTo methods. Each of these methods is asynchronous and returns the Task <bool> object.By default, each animation takes 250 milliseconds. However, a duration for each animation can be specified when creating the animation. Animation methods should generally be used with the await operator, which allows you to easily determine when an animation is completed. However, if there’s a requirement to let an animation complete in the background, then the await operator may not be used.

For change the color of slider we should add below lines to AppDelegate.cs file:

UISlider.Appearance.TintColor = UIColor.FromRGBA(255, 160, 0, 255);
UISlider.Appearance.ThumbTintColor = UIColor.FromRGBA(255, 160, 0, 255);
iOS
Android

You can download github project here.

Article suggestion: https://blog.xamarin.com/creating-animations-with-xamarin-forms/

--

--