更改细节公开按钮的图像(Xcode 4.2)

时间:2011-10-17 18:20:33

标签: xcode uitableview ios5

我使用了以下建议的例程来更改表格视图单元格中的详细信息公开按钮图像(在tableView中的cellForRowAtIndexPath)

if (cell == nil) {

    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];

    UIButton *myAccessoryButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 24, 24)];
    [myAccessoryButton setBackgroundColor:[UIColor clearColor]];
    [myAccessoryButton setImage:[UIImage imageNamed:@"ball"] forState:UIControlStateNormal];
    [cell setAccessoryView:myAccessoryButton];
    cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
}

但是,单击按钮后现在不再调用事件tableView accessoryButtonTappedForRowWithIndexPath

有没有人想过为什么?

1 个答案:

答案 0 :(得分:6)

我已经给弗莱的答案+1了,但是只是为了从其他网站提取代码来使SO更加完整:答案是你必须使用accessoryButtonTapped ....不会自动调用,因为它对于内置的细节披露,你必须自己使用按钮的目标。

从链接代码翻译到上面的示例,在setImage:

之后添加此行
[myAccessoryButton addTarget:self action:@selector(accessoryButtonTapped:event:)  forControlEvents:UIControlEventTouchUpInside];

然后稍后再添加:

- (void)accessoryButtonTapped:(id)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 (indexPath != nil) {
        [self tableView: self.tableView accessoryButtonTappedForRowWithIndexPath: indexPath];
    }
} 

(从this link逐字复制)

请注意,这假设按钮是在UITableViewController中创建的(在我的情况下,我在自定义单元格中创建一个,因此引用略有不同)

说明:accessoryButtonTapped是我们自定义按钮的自定义目标方法。当按下按钮(“TouchUpInside”)时,我们在发生按下的位置找到单元格的indexPath,并调用表视图通常会调用的方法。