点按时UITableView自定义配件按钮图像消失

时间:2011-07-01 07:30:23

标签: ios iphone objective-c

我有一个带有自定义配件按钮的UITableView,如下所示:

cellForRowAtIndexPath方法中,我执行以下操作:

  ...
  UIButton *myAccessoryButton =[[[UIButton alloc] init] autorelease];   
  myAccessoryButton =[self makeAccessoryButton: @"arrow2.png"];
 [cell setAccessoryView:myAccessoryButton];
 return cell;

并且函数makeAccessoryButton定义如下:

- (UIButton *) makeAccessoryButton: (NSString *) imageName
{

UIButton *myAccessoryButton = [[UIButton buttonWithType:UIButtonTypeCustom] autorelease];
CGRect frame = CGRectMake(0, 0, 24, 24);
myAccessoryButton.frame = frame;
[myAccessoryButton setBackgroundColor:[UIColor clearColor]];
[myAccessoryButton setImage:[UIImage imageNamed:imageName] forState: UIControlStateNormal];
[myAccessoryButton addTarget: self
                      action: @selector(accessoryButtonTapped:withEvent:)
            forControlEvents: UIControlEventTouchUpInside];
//myAccessoryButton.userInteractionEnabled = YES;
return ( myAccessoryButton );

}

并且函数定义如下:

 - (void) accessoryButtonTapped: (UIControl *) button withEvent: (UIEvent *) event
{   
NSLog(@"testing ...");
}

现在问题是:当我点击此按钮时,只有当行突出显示时,其图像才会消失,我为该按钮尝试了状态UIControlStateNormalUIControlStateHighlighted,但问题仍然存在,如我所说。如果在未选择(或突出显示)表格视图行的情况下点击该按钮,则按钮图像不会出现任何问题(它不会消失)。我该如何解决这个问题?

4 个答案:

答案 0 :(得分:0)

在自定义附件按钮中添加UIControlStateHighlightedUIControlStateSelected的图片。

[myAccessoryButton setImage:[UIImage imageNamed:imageName] forState:UIControlStateHighlighted];

答案 1 :(得分:0)

这也让我发疯了!

这里出现的问题是UIButton继承了所选状态,然后它的imageView的选定状态设置错误。

要修复它,请继承UITableViewCell并覆盖setSelected方法

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    if ([self.accessoryView isKindOfClass:[UIButton class]])
    {
        UIButton *button = (UIButton*) self.accessoryView;
        [[button imageView] setHighlighted:NO];
    }
}

答案 2 :(得分:0)

您正在此行中自动释放自动释放的对象

UIButton *myAccessoryButton = [[UIButton buttonWithType:UIButtonTypeCustom] autorelease];

虽然它应该像

UIButton *myAccessoryButton = [UIButton buttonWithType:UIButtonTypeCustom];

也代替此代码

UIButton *myAccessoryButton =[[[UIButton alloc] init] autorelease];   
  myAccessoryButton =[self makeAccessoryButton: @"arrow2.png"];
 [cell setAccessoryView:myAccessoryButton];
 return cell;

你可以这么简单地做到这一点

 [cell setAccessoryView:[self makeAccessoryButton: @"arrow2.png"]];
 return cell;

尝试上述建议,并为所有三种状态设置图像

[myAccessoryButton setImage:[UIImage imageNamed:imageName] forState: UIControlStateNormal];

[myAccessoryButton setImage:[UIImage imageNamed:imageName] forState: UIControlStateHighlighted];

[myAccessoryButton setImage:[UIImage imageNamed:imageName] forState: UIControlStateSelected];

让我知道这是否有效。

答案 3 :(得分:0)

只需设置UIButton即可。 IB中相同图像的所有4种状态的图像。

请注意,从列表中选择图像或键入名称时,请确保单击文本字段。 IB似乎没有保存价值。

返回所有4个州并检查保存的图像名称。