iphone - 当单元格突出显示时,uibutton 图像不会改变

标签 iphone objective-c uitableview uibutton

我的表格 View 的每个单元格中都有一个自定义 UI 按钮。这个 UI 按钮的工作原理类似于 Gmail 等中使用的 STAR 按钮的“添加到收藏夹”功能。意味着每当我单击该按钮时,相应的项目就会添加到收藏夹列表中,并且按钮的图像会更改为发光的星星图像。再次单击它时,该项目将从收藏夹列表中删除,并使用空星作为其图像。

我在这里面临的问题是,当我选择单元格时,它总是显示按钮的空图像,而不是突出显示的星形图像。

注意,如果tableview的分隔符样式设置为NONE,这个问题就可以解决。 但我确实想要分隔符样式。

如果可以的话请帮忙。

最佳答案

使用此代码更改正常和选定状态下的按钮图像。如果你想添加收藏夹列表,那么你需要获取按钮索引值。

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

    customBtn = [UIButton buttonWithType:UIButtonTypeCustom]; 
    customBtn.frame = CGRectMake(292, 8.0, 30, 28); 

    UIImage *likeSelectedImage = [UIImage imageNamed:@"star off.png"];

   [customBtn setBackgroundImage:likeSelectedImage forState:UIControlStateNormal];

    [customBtn addTarget:self action:@selector(addToFavouriteClicked1:) forControlEvents:UIControlEventTouchUpInside]; 
    customBtn.tag = indexPath.row; 
    [cell.contentView addSubview:customBtn];
}


-(void) addToFavouriteClicked1 : (id) sender
{
    UIImage *likeSelectedImg = [UIImage imageNamed:@"star on.png"];

    UIImage *likeImg = [UIImage imageNamed:@"star off.png"];

    if ([sender isSelected]) {
        [sender setImage:likeImg forState:UIControlStateNormal];
        [sender setSelected:NO];
    }else {
        [sender setImage:likeSelectedImg forState:UIControlStateSelected];
        [sender setSelected:YES];
    } 
}

关于iphone - 当单元格突出显示时,uibutton 图像不会改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5324485/

相关文章:

iphone - 使用 sizeWithFont 时的高度 :constrainedToSize:lineBreakMode with NSLineBreakByTruncatingTail

objective-c - 如何比较 coredata 字符串和 NSString

ios - 将多个 UIButton 组合成一个按钮

ios - 如何调试我的 iOS 应用程序中的卡住问题

iphone - 在不向右移动单元格内容的情况下显示 UITableViewCell 重新排序控件?

ios - UITableViewCell 内部的程序化自动布局更改仅在方向更改后更新

iphone - 在 Objective-C 中使用单例声明全局变量

ios - 从服务中获取数据 Objective c

iphone - 在 View 中设置 searchBar.text 确实加载了

iphone - UITableview 只允许单向滑动删除