Create a Horizontal Scrolling Button List

PDF for offline use
Sample Code:
Related Articles:
Related SDKs:

Let us know how you feel about this

Translation Quality


0/250

This recipe shows how to create a horizontal scrolling list of buttons.

Recipe

Follow these steps to create a scrolling list of buttons in a UIViewController subclass:

  1. Declare UIScrollView and List<UIButton> class variables.
UIScrollView scrollView;
List<UIButton> buttons;
  1. Instantiate the button list List<UIButton> in the constructor.
public ScrollingButtonsController ()
{
    buttons = new List<UIButton> ();
}
  1. Initialize parameters for laying out the buttons.
public override void ViewDidLoad ()
{
    base.ViewDidLoad ();

    nfloat h = 50.0f;
    nfloat w = 50.0f;
    nfloat padding = 10.0f;
    nint n = 25;

    …
}
  1. Create the UIScrollView
scrollView = new UIScrollView {
                Frame = new CGRect (0, 100, View.Frame.Width, h + 2 * padding),
                ContentSize = new CGSize ((w + padding) * n, h),
                BackgroundColor = UIColor.White,
                AutoresizingMask = UIViewAutoresizing.FlexibleWidth
            };
  1. Create buttons and add them to the scroll view.
for (int i=0; i<n; i++) {
        var button = UIButton.FromType (UIButtonType.RoundedRect);
        button.SetTitle (i.ToString (), UIControlState.Normal);
        button.Frame = new CGRect (padding * (i + 1) + (i * w), padding, w, h);
        scrollView.AddSubview (button);
        buttons.Add (button);
    }
  1. Add the UIScrollView as a subview.
View.AddSubview (scrollView);

Additional Information

The UIScrollView will scroll when the ContentSize is greater than the size defined by the UIScrollView.Frame. Try experimenting with the layout parameters in the step 3 to see the effect it has on the button list that is created.

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.