Необходимо выполнить действие для нажатия UIButton во вложенных табличных представлениях с пользовательским UITableViewCell - PullRequest
0 голосов
/ 09 февраля 2012

У меня есть UITableViewController (называется детали). В этом табличном представлении в строке 1 у меня есть другой UITableView, который я вращаю горизонтально. Каждая ячейка в этом табличном представлении представляет собой пользовательский UITableViewCell (называемый DetailsHorizontPhotoCell), который отображает кнопку с изображением. Мне трудно предпринимать какие-либо действия, когда нажимаются фотографии (кнопки).

Вызов IBAction для меня не проблема, если у меня есть этот код IBAction в файлах DetailsHorizontPhotoCell.h / .m, однако мне нужно представить модальный VC при нажатии кнопки. Этот код не принадлежит и / или не работает в tableViewCell - он должен быть в контроллере (Подробности). При этом я не могу понять, как его кодировать. Это то, что я имею до сих пор.

Details.m:

if( (indexPath.row == 1) && ([detailsObject_.photo count] > 0) )
{
    NSLog(@"** In Photo Section **");

    static NSString *CellIdentifier = @"cellPhoto";
    DetailsHorizontalPhotoCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil)
    {
        cell = [[DetailsHorizontalPhotoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    CGAffineTransform rotateTable = CGAffineTransformMakeRotation(-M_PI_2);
    cell.horizontalTableView.transform = rotateTable;

    NSArray *photoArray = [[NSArray alloc] initWithArray:detailsObject_.photo];

    cell.horizontalTableView.frame = CGRectMake(0, 0, cell.horizontalTableView.frame.size.width, cell.horizontalTableView.frame.size.height); 
    cell.contentArray = [NSArray arrayWithArray:photoArray];
    cell.horizontalTableView.allowsSelection = YES;

    return cell;
}

DetailsHorizontalPhotoCell.m:

@synthesize horizontalTableView = horizontalTableView_;
@synthesize contentArray = contentArray_;
@synthesize imageButton = imageButton_;

// *** a bunch of code which is not relevant to this question snipped out here... 


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [self.horizontalTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    }

    for(UIButton *button in cell.subviews)
    {
        [button removeFromSuperview];
    }

    // create image and button
    UIImage *image = [UIImage imageNamed:[contentArray_ objectAtIndex:indexPath.row]];
    self.imageButton = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, 240, 240)];

    // setup the button
    [imageButton_ setImage:image forState:UIControlStateNormal];
    imageButton_.layer.masksToBounds = YES;
    imageButton_.layer.cornerRadius = 5.0;
    imageButton_.layer.borderWidth = 1.0;
    imageButton_.layer.borderColor = [[UIColor grayColor] CGColor];

    // rotate the button
    CGAffineTransform rotateButton = CGAffineTransformMakeRotation(M_PI_2);
    imageButton_.transform = rotateButton;

    // this detects the click of each photo and triggers the IBAction
    [imageButton_ addTarget:self action:@selector(photoButton:) forControlEvents:UIControlEventTouchUpInside];

    /// do more stuff yada yada yada... <snipped code> and return cell;
}


// the Action (which I know should NOT be in this UITableViewCell class)
- (IBAction)photoButton:(id)sender 
{
    CGPoint hitPoint = [sender convertPoint:CGPointZero toView:self.horizontalTableView];
    NSIndexPath *hitIndex = [self.horizontalTableView indexPathForRowAtPoint:hitPoint];

    NSLog(@"Image clicked, index: %d", hitIndex.row);

    // presentModalViewController here - but you can't do that from here! Must be in the Details controller
}

Итак, зная, что я не могу выполнить presentModalViewController из ячейки, я пытаюсь переместить этот код в класс Details (ниже)

Добавьте IBAction к Details.h и .m

- (IBAction)photoButton:(id)sender 
{
    DetailsHorizontalPhotoCell *cell = [[DetailsHorizontalPhotoCell alloc] init];

    CGPoint hitPoint = [sender convertPoint:CGPointZero toView:cell.horizontalTableView];
    NSIndexPath *hitIndex = [cell.horizontalTableView indexPathForRowAtPoint:hitPoint];

    NSLog(@"Image clicked, index: %d", hitIndex.row);
}

И добавьте событие click к кнопке с фото в методе Details cellForRowAtIndexPath.

// Blaaahh! Tried a million combinations of something like below but cannot get it to work... 
//[cell.imageButton addTarget:cell.horizontalTableView action:@selector(photoButton:) forControlEvents:UIControlEventTouchUpInside];

PS - я использую IOS5, Xcode 4.2 с ARC

Ответы [ 3 ]

1 голос
/ 10 февраля 2012

У вас проблемы с распознаванием нажатия кнопки или у вас не получается заставить presentModalViewController работать с таблицей? Если у вас возникли проблемы с обнаружением нажатия кнопки, вам может понадобиться:

[button setExclusiveTouch:YES];

Если у вас возникли проблемы из-за того, что вы не можете использовать presentModalViewController из tableView, тогда вы можете использовать:

[[NSNotificationCenter defaultCenter] addObserver: selector: name: object:];

Чтобы уведомить свой "Класс данных" для использования presentModalViewController

1 голос
/ 09 февраля 2012

Прежде всего, нет необходимости добавлять кнопку каждый раз, когда отображается ячейка.Вам нужно только добавить подпредставления ячейки при создании новой ячейки.Таким образом вы улучшите производительность прокрутки.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [self.horizontalTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

        // Add image button to cell
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(5, 5, 240, 240)];
        // set tag so you can get the button later
        button.tag = 1021;
        [button addTarget:self action:@selector(photoButton:) forControlEvents:UIControlEventTouchUpInside]
        // more button config
        [cell.contentView addSubView:button];
    }
    // get image button
    UIButton *button = [cell.contentView viewWithTag:1021];
    // configure image button
    UIImage *image = [UIImage imageNamed:[contentArray_ objectAtIndex:indexPath.row]];
    [button setImage:image forState:UIControlStateNormal];
    return cell;
}

Далее вы можете использовать superview на кнопке (= отправитель), чтобы вернуться к UITableViewCell.С помощью ячейки вы можете получить indexPath этой ячейки.

- (IBAction)photoButton:(id)sender 
{
    UIView *contentView = [sender superview];
    UITableViewCell *cell = [contentView superview];
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
}
0 голосов
/ 09 февраля 2012

вы можете добавить определенный тег или доступ к uitableview с помощью [[button superview] superview]

...