Вращение с UITableViewCell - PullRequest
0 голосов
/ 02 марта 2011

У меня есть следующий код, который создает мой UITableViewCell ...

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSNumberFormatter *numberFormatter = nil;
    if (numberFormatter == nil) {
        numberFormatter = [[NSNumberFormatter alloc] init];
        [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
        [numberFormatter setMaximumFractionDigits:3];
    }

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];

        UIImage *image = [UIImage imageNamed:@"home1"];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        CGRect frame = CGRectMake(0.0, 0.0, image.size.width, image.size.height);
        button.frame = frame;
        button.tag = indexPath.row;
        [button setBackgroundImage:image forState:UIControlStateNormal];
        [button addTarget:self action:@selector(setHomeButtonTapped:)  forControlEvents:UIControlEventTouchUpInside];
        button.backgroundColor = [UIColor clearColor];
        cell.accessoryView = button;

        UIImage *imageShare = [UIImage imageNamed:@"arrows-share"];
        UIButton *buttonRight = [UIButton buttonWithType:UIButtonTypeCustom];
        buttonRight.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
        [buttonRight setBackgroundImage:imageShare forState:UIControlStateNormal];
        [buttonRight setFrame: CGRectMake( 220.0f, 0.0f, imageShare.size.width, imageShare.size.height)];
        [buttonRight addTarget:self action:@selector(shareLink:) forControlEvents:UIControlEventTouchUpInside];

        [cell addSubview:buttonRight];
    }

    Event *event = (Event *)[eventsArray objectAtIndex:indexPath.row];

    cell.textLabel.text = [event name];

    NSString *string = [NSString stringWithFormat:@"%@, %@",
                        [numberFormatter stringFromNumber:[event lat]],
                        [numberFormatter stringFromNumber:[event lon]]];
    cell.detailTextLabel.text = string;

    return cell;
}

Это прекрасно работает в портретной, но в альбомной ориентации, когда повернутая кнопка UIB "buttonRight" не остается рядом с дополнительным видом.Возможно ли это без создания всего этого в IB?

enter image description here

Ответы [ 2 ]

2 голосов
/ 02 марта 2011

Вы должны быть в состоянии достигнуть этого, вычисляя свою позицию x вместо жесткого кодирования в 220.0. Определите некоторые константы для ширины и высоты ваших изображений и буфера.

CGPointMake buttonOrigin = CGPointMake(cell.frame.size.width - kHomeButtonWidth - kShareButtonWidth - (kBufferWidth * 2), (cell.frame.size.height - kShareButtonHeight) / 2);
CGRect buttonFrame = CGRectMake(buttonOrigin.x, buttonOrigin.y, kShareButtonWidth, kShareButtonHeight);
[buttonRight setFrame:buttonFrame];
1 голос
/ 02 марта 2011

Попробуйте заменить:

buttonRight.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;

с

buttonRight.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;

Это должно помочь при повороте из портрета в пейзаж. Однако жестко запрограммированный 220 вызовет проблемы, когда ячейки будут инициализированы в ландшафтном режиме.

Необходимо рассмотреть четыре случая:

  1. Инициализируется в портретном режиме
  2. Инициализируется в портретном режиме, затем поворачивается в альбомную ориентацию.
  3. Инициализирован в ландшафтном режиме
  4. Инициализируется в ландшафтном режиме, затем поворачивается в портрет.

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...