简体   繁体   中英

A custom Button in a UITableViewCell

I have a UITableView with three section. I have a custom UITableViewCell . I want to put a button in the first section of my table view to handle an action.

How to can do this please?

just create the button programmatically

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self 
           action:@selector(aMethod:)
 forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[view addSubview:button];

If you want to put it in the section header (rather than a cell), you could:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if(section==0)
    {
        // create button and return it
    }
}

You can also put the button directly into a UITableViewCell which is located in your first section. In your cellForRowAtIndexPath you can use for example:

    UIButton *yourButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [yourButton setTitle:@"Click me" forState:UIControlStateNormal];
    [yourButton setFrame: CGRectMake( 20.0f, 3.0f, 280.0f, 33.0f)];
    [yourButton addTarget:self action:@selector(clickAction) forControlEvents:UIControlEventTouchUpInside];

    [cell addSubview:yourButton];

This example will look like this:

在此处输入图像描述

and will be places directly in the cell.

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