【问题标题】:I need to make a favorite button and change the image when click我需要制作一个收藏按钮并在单击时更改图像
【发布时间】:2014-11-04 14:15:31
【问题描述】:

我创建了一个带有星形图像的按钮,我需要在单击时更改图像。比如点击按钮收藏,再次点击删除收藏。

这是代码

 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];


if (cell == nil)
{
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                  reuseIdentifier:@"Cell"];

}
favButton = [UIButton buttonWithType:UIButtonTypeCustom];
[favButton addTarget:self action:@selector(buttonClicked:)   forControlEvents:UIControlEventTouchUpInside];
[favButton setBackgroundImage:[UIImage imageNamed:@"stardes.png"] forState:UIControlStateNormal];
favButton.frame = CGRectMake(200, 90, 20, 25);
[cell.contentView addSubview:favButton];

return cell;
}

【问题讨论】:

  • 将它的图像设置为 buttonClicked 中的新图像?
  • 但是这种方法不起作用,因为当单元格被重绘时,它会再次用原始图像重绘。您需要保留“收藏”索引路径的列表,并在布局单元格时根据该索引路径是否“收藏”来选择和图像

标签: objective-c xcode ios7


【解决方案1】:

您必须将状态存储在某处。它通常存储在一个由 indexPath 索引的数组(yourdataset)中,我注意到你没有使用它。除了在点击时更改图像,您还需要在数组中设置状态。 在buttonClicked方法中,迭代superView,直到到达被点击按钮的UITableViewCell,找到在table中的位置。现在您有了要更改的数组中数据的索引。

之后,只需检查设置背景图像之前的状态即可。像这样的:

MyData* dta = self.myData[ indexPath.row ];
if (dta.favorite)
    [favButton setBackgroundImage:[UIImage imageNamed:@"stardes.png"] forState:UIControlStateNormal];
else
    [favButton setBackgroundImage:[UIImage imageNamed:@"stardes2.png"] forState:UIControlStateNormal];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-07
    • 1970-01-01
    • 2013-11-05
    • 1970-01-01
    • 2020-04-30
    • 1970-01-01
    • 2018-04-14
    相关资源
    最近更新 更多