You should probably look into using a UITableView
before attempting an application that requires this.
I've written this from memory so please test it and confirm it all works...
Make sure your view controller implements the methods from the table view delegates, and declare a UITableView
obj and a array like so:
@interface YourTableViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
{
IBOutlet UITableView *theTableView;
NSMutableArray *theArray;
}
Make sure you link them in your storyboard. You should see theTableView
as defined above.
When you application loads, write this (somewhere like viewDidLoad
would be fine):
theArray = [[NSMutableArray alloc] initWithObjects:@"Item 1", @"Item 2", @"Item 3", nil];
You do not need to declare how many sections there are in your table view, so for now ignore this until later. You should however, declare how many rows there are:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [theArray count]; // Return a row for each item in the array
}
Now we need to draw the UITableViewCell
. For simplicity we will use the default one, but you can make your own quite easily.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// This ref is used to reuse the cell.
NSString *cellIdentifier = @"ACellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
// Set the cell text to the array object text
cell.textLabel.text = [theArray objectAtIndex:indexPath.row];
return cell;
}
Once you have the table displaying the track names, you can use the method:
(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.row == 0)
{
NSString *arrayItemString = [theArray objectAtIndex:indexPath.row];
// Code to play music goes here...
}
}
In the NSMutableArray
we declared at the top, you do not have to add NSString
's to the array. You can make your own object if you want to store multiple strings for example. Just remember to modify where you call the array item.
Finally, to play the audio, try using the answer in this SO answer.
Also, while it's not necessary, you could use a SQLite database to store the tracks you wish to play in a list rather than hard coding the list. Then fill the NSMuatableArray
after calling the database.