我们如何在自定义单元格中添加按钮?

时间:2011-09-02 12:15:40

标签: iphone

我在应用程序中工作,需要通过customcell在单元格中添加按钮。 任何人都可以帮我吗? 提前致谢

1 个答案:

答案 0 :(得分:0)

您在Customcell中添加了一个按钮,因此请使用以下代码。         首先,添加带有UITableViewCell子类的新文件然后         Customcell.h文件                @interface CustomCell:UITableViewCell                {                  UIButton * customButton;                }     @property(非原子,保留)UIButton * customButton;

           Customcell.m
@implementation CustomCell;
           @synthesize customButton;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier 
{
    if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) 
    {
          customButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [customButton setImage:[UIImage imageNamed:@"phonecall.png"] forState:UIControlStateNormal];
         }
         return self;
}

// set layout in subview
- (void)layoutSubviews 
{

    [super layoutSubviews];

    CGRect contentRect = self.contentView.bounds;

    CGFloat boundsX = contentRect.origin.x;

    CGFloat boundY = contentRect.origin.y;

    CGRect frame1;

        frame1 = CGRectMake(boundsX+10, boundY+58, 19, 18);
    customButton.frame = frame1;

}

#import "CustomCell.h"
In cellForRowAtIndexPath method

// Customize the number of cells in the table view.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
    static NSString *CellIdentifier = @"Cell";

    CustomCell *cell= [[[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];

    if (cell == nil) 
    {
        cell = [[[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }

    [cell.customButton addTarget:self action:@selector(callAction:) forControlEvents:UIControlEventTouchUpInside];
return cell;
}