我有一个动态表格 View ,其中有一个带有按钮的原型(prototype)单元格,按下该按钮即可播放歌曲。
我希望当用户按下按钮播放歌曲时,按钮上的背景图像更改为“停止”图标,当用户按下一次时,按钮上的背景图像更改为“播放”图标再次停止歌曲。
为了实现这一点,我一直在尝试使用:
[self.beatPlayButton setBackgroundImage:[UIImageimageNamed:@"play.png"]forState:UIControlStateNormal];
我的问题是,由于我使用的是原型(prototype)单元,所以我还没有弄清楚如何仅更改正在按下的行中的按钮。我一直希望找到像 didSelectObjectAtRow:atIndexPath:
这样的方法,因为 didSelectRowAtIndexPath:
会在按下行时触发,但不会触发其上的按钮(除非我错误)。也许我应该使用标签?我不知道。任何指示将不胜感激。
编辑:
我的代码位于 didSelectRowAtIndexPath
之外。
这是示例代码-
- (IBAction)playStopBeat:(UIButton*)sender event:(id)event {
NSSet *touches = [event allTouches];
UITouch *touch = [touches anyObject];
CGPoint currentTouchPosition = [touch locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint: currentTouchPosition];
if([self.audioPlayer isPlaying])
{
[self.beatPlayButton setBackgroundImage:[UIImage imageNamed:@"play.png"]forState:UIControlStateNormal];
[self.audioPlayer stop];
self.isPlaying = NO;
self.audioPlayer = nil;
}
else {
if (indexPath.row == 0) {
[self.beatPlayButton setImage:[UIImage imageNamed:@"stop.png"] forState: UIControlStateNormal];
}
else if (indexPath.row == 1){
[self.beatPlayButton setBackgroundImage:[UIImage imageNamed:@"stop.png"]forState:UIControlStateNormal];
}
else if (indexPath.row == 2){
...
//code to play song
最佳答案
按照您的建议使用标签。在您的 cellForRowAtIndexPath
方法中为每个单元格指定一个标签:
cell.tag = indexPath.row;
还在单元格上设置每个目标:
[cell.playButton addTarget:self action:@selector(play:)forControlEvents:UIControlEventTouchUpInside];
然后在您的播放方法中,使用您的数组标签或w/e:
- (IBAction)play:sender
{
UITableViewCell *cell = (UITableViewCell *)sender;
NSLog(@"tag = %d", cell.tag);
if(tag == 0)
{
//you could also use a switch statement
} else if(tag == 1) {
}
}
::编辑::(评论的答案)
要在您的播放方法中禁用其他按钮:
- (IBAction)play:sender
{
.........
....other code....
UITableViewCell *cell = (UITableViewCell *)sender;
for(int i = 0; i < [dataArray count]; i++)
{
UITableViewCell *tempCell = [tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
if(tempCell.tag != cell.tag)
{
[cell.playButton setEnabled:NO];
}
}
}
在执行此操作时,歌曲播放完毕后,您必须将它们全部设置回启用状态。这将在 MediaPlayers 委托(delegate)方法中完成:didFinishPlaying。
关于iphone - 更改 UITableview 中按下的特定按钮的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11299057/