I have a UIScrollView and a UIPageControl on my View in my iPhone app. I populate this Scrollview with a list of 10 buttons. The buttons all populate correctly an I can scroll through them perfectly. My question is: How do I wire up a click event to each of those buttons? Each button will perform essentially the same task (Play a sound) however the sound will be different for each of these buttons. The buttons are created programatically by the following method:
private void CreatePanels()
{
scrollView.Scrolled += ScrollViewScrolled;
int count = 10;
RectangleF scrollFrame = scrollView.Frame;
scrollFrame.Width = scrollFrame.Width * count;
scrollView.ContentSize = scrollFrame.Size;
for (int i=0; i<count; i++)
{
float h = 150.0f;
//float w = 50.0f;
float padding = 10.0f;
int n = 25;
var button = UIButton.FromType (UIButtonType.RoundedRect);
button.SetTitle (i.ToString (), UIControlState.Normal);
UIImage img = new UIImage("Images/btntest.png");
button.SetImage(img, UIControlState.Normal);
button.Frame = new RectangleF (
(padding + 40) * (i + 1) + (i * (View.Frame.Width - 100)) ,
padding,
View.Frame.Width - 100,
h);
RectangleF frame = scrollView.Frame;
PointF location = new PointF();
location.X = frame.Width * i;
frame.Location = location;
button.Frame = frame;
scrollView.AddSubview(button);
}
pageControl.Pages = count;
}
private void ScrollViewScrolled (object sender, EventArgs e)
{
double page = Math.Floor(((scrollView.ContentOffset.X - scrollView.Frame.Width) / 2) / scrollView.Frame.Width) + 1;
pageControl.CurrentPage = (int)page;
}
The CreatePanels() method is called within the ViewDidLoad() method which populates the UIScrollView.
How can I link a click event to each of these buttons? I have searched the internet a lot but to no avail.
What about wiring up an anonymous method to each click event in the for loop?
button.TouchUpInside += (s, e) =>
{
//play i.mp3
};
I'm not sure how to actually play a sound file but you could have your sound files named as i.* since that is what your buttons are named.