简体   繁体   中英

Add a Button to a TableView Cell:

I have a UI tableView and I am trying to create a button like the one used in the Safari Settings to Clear History:

在此处输入图片说明

The code I have tried doesnt really work and I'm sure there is a better way:

        case(2):
           // cell = [[[ButtonLikeCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];


            if (indexPath.row == 0) 
            {            
                UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                [button setFrame:cell.bounds]; 
                [button addTarget:self action:@selector(clearButtonClick) forControlEvents:UIControlEventTouchUpInside];
                [button setBackgroundColor:[UIColor purpleColor]];
                [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                [button setTitle:@"Clear Data" forState:UIControlStateNormal];
                cell.accessoryView = nil;
                cell.clipsToBounds=YES;
                [cell.contentView addSubview:button];
            }

            break;
    }
}

return(cell);

}

A subclass on the tableview cell is overkill for this, basically all you need to do is set the text alignment of the textLabel to center

case(2):
        if (indexPath.row == 0) 
        {   
            cell.textLabel.textAlignment = UITextAlignmentCenter;
        }
        break;

no need to use an actual UIButton.

the only difference between does rows and "normal" rows is the position of the label. subclass UITableViewCell and override -laysubviews to center the label and you're done, like so:

@interface ButtonLikeCell : UITableViewCell

@end

@implementation ButtonLikeCell

-(void)layoutSubviews
{
    self.titleLabel.center = self.center;
}

@end

this will reposition the label of the cell and make it look similar to what you're looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM