在尝试需要此功能的应用程序之前,您可能应该考虑使用UITableView。
我是凭记忆写的,所以请测试一下并确认一切正常......
确保您的视图控制器实现表视图委托的方法,并声明一个UITableView obj 和一个数组,如下所示:
@interface YourTableViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
{
IBOutlet UITableView *theTableView;
NSMutableArray *theArray;
}
确保在故事板中链接它们。您应该看到上面定义的theTableView。
当你加载应用程序时,写下这个(像viewDidLoad 这样就可以了):
theArray = [[NSMutableArray alloc] initWithObjects:@"Item 1", @"Item 2", @"Item 3", nil];
您不需要声明表格视图中有多少个部分,所以现在暂时忽略这一点,直到以后。但是,您应该声明有多少行:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [theArray count]; // Return a row for each item in the array
}
现在我们需要绘制UITableViewCell。为简单起见,我们将使用默认的,但您可以很容易地制作自己的。
- (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;
}
一旦有了显示曲目名称的表格,就可以使用以下方法:
(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.row == 0)
{
NSString *arrayItemString = [theArray objectAtIndex:indexPath.row];
// Code to play music goes here...
}
}
在我们在顶部声明的NSMutableArray 中,您不必将NSString 添加到数组中。例如,如果您想存储多个字符串,您可以创建自己的对象。只需记住修改调用数组项的位置即可。
最后,要播放音频,请尝试使用this SO answer中的答案。
此外,虽然这不是必需的,但您可以使用 SQLite 数据库将您希望播放的曲目存储在一个列表中,而不是对列表进行硬编码。然后调用数据库后填写NSMuatableArray。