如何在iOS 8.3中自定义删除按钮

时间:2015-08-07 10:06:36

标签: ios objective-c uitableview

- (void)willTransitionToState:(UITableViewCellStateMask)state
{
    [super willTransitionToState:state];
    if ((state & UITableViewCellStateShowingDeleteConfirmationMask) == UITableViewCellStateShowingDeleteConfirmationMask)
    {
        for (UIView *subview in self.subviews)
        {
            if ([NSStringFromClass([subview class]) isEqualToString:@"UITableViewCellDeleteConfirmationControl"])
            {
                UIImageView *deleteBtn = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 64, 33)];
                [deleteBtn setImage:[UIImage imageNamed:@"CROSS.png"]];
                [[subview.subviews objectAtIndex:0] addSubview:deleteBtn];
            }
        }
    }
}

我正在尝试在tableview中添加删除按钮的图像 但无法弄清楚请帮助我。 提前谢谢。

2 个答案:

答案 0 :(得分:0)

使用此块并在 self.view 中写下 aMethod 正文 并将此方法写入 CellForRowAtIndexPath

- (UITableViewCell *)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* cellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

  UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  [button addTarget:self action:@selector(aMethod:) forControlEvents:UIControlEventTouchUpInside];
  button.frame = CGRectMake(0, 0, 64, 33);
  [button setImage:[UIImage imageNamed:@"CROSS.png"]];
  [cell.view addSubview:button];

 // Write your own code here

  return cell;
}

答案 1 :(得分:0)

您需要对UITableViewCell进行子类并覆盖布局子视图方法

- (void)layoutSubviews
{
    [super layoutSubviews];

    UIView *deleteButton = nil;


    if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.0) {
        //for os version less than iOS 8, i.e., iOS 7
        BOOL shouldStop = NO;
        for (UIView *subview in self.subviews) {
            for (UIView *subview2 in subview.subviews) {
                if ([NSStringFromClass([subview2 class]) isEqualToString:@"UITableViewCellDeleteConfirmationView"]) {
                    deleteButton = subview2;
                    shouldStop = YES;
                    break;
                }
            }
            if (shouldStop)
                break;
        }

    } else {
        //for iOS 8
        for (UIView *subview in self.subviews) {
            if ([NSStringFromClass([subview class]) isEqualToString:@"UITableViewCellDeleteConfirmationView"]) {
                deleteButton = subview;
                break;
            }
        }

    }

    if (deleteButton) {
        UIImageView *deleteBtn = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 64, 33)];
        [deleteBtn setImage:[UIImage imageNamed:@"cross.png"]];
        [[deleteButton.subviews objectAtIndex:0] addSubview:deleteBtn];
    }



}