Пользовательский UITableViewCell в режиме редактирования не перемещает мои UILabels

Это делает мою голову в:-)

У меня полнофункциональный CoreData заполнен UITableView внутри UIViewController и я успешно реализовал "Размах для удаления" (что легко), и я также могу удалить отдельные экземпляры с помощью кнопки редактирования, когда появляется красный кружок.

Моя проблема, и я думаю, это потому, что у меня есть CustomCell, что, когда я нажимаю кнопку редактирования UILabels не двигайтесь вправо.

Я пытался использовать -(void)layoutSubViews и несколько других, но ничего не работает.

Я разместил свой код для моего cellForRowAtIndexPath, Это часть заметки в моем приложении. Этот код работает, мне просто нужно знать, как переместить метки, когда я вхожу в режим редактирования??

Спасибо за советы и рекомендации:-)

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

MNCustomCell *cell = [_mainTableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
if (cell == nil) {
    cell = [[MNCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}


//cell.textLabel.text = [_tableArray objectAtIndex:indexPath.row];

MNotes *mnotes = [[self fetchedResultsController] objectAtIndexPath:indexPath];

cell.noteTitle.text = mnotes.noteTitleString;
cell.noteSummary.text = mnotes.mainNoteString;

mnotes.createDate = [[NSDate alloc] init];
SORelativeDateTransformer *relativeDateTransformer = [[SORelativeDateTransformer alloc] init];
NSString *relativeDate = [relativeDateTransformer transformedValue:mnotes.createDate];

cell.noteDate.text = relativeDate;


cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

return cell;
}

-

//This is the Custom Cell
@interface MNCustomCell : UITableViewCell
{

}

@property (strong, nonatomic) IBOutlet UILabel *noteTitle;
@property (strong, nonatomic) IBOutlet UILabel *noteDate;

@property (strong, nonatomic) IBOutlet UITextView *noteSummary;


@end

-

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
  {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
    // Initialization code

    [self.contentView addSubview:_noteTitle];
    [self.contentView addSubview:_noteSummary];
    [self.contentView addSubview:_noteDate];

  }
   return self;
  }

2 ответа

Решение

Другое решение, вероятно, будет работать, но этот способ автоматически сделает анимацию для вас.MNCustomCell не собирается переупорядочивать представление в зависимости от текущего состояния ячейки, но если вы добавите свою метку в contentView ячейки, это произойдет.

В следующем примере метка будет перемещена, чтобы она не мешала кнопке удаления.

MNCustomCell.m

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        mainLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 220.0, 15.0)]];
        mainLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
        [cell.contentView addSubview:mainLabel];

Реализуйте следующие методы в своем пользовательском классе ячеек.

- (void)willTransitionToState:(UITableViewCellStateMask)state 

а также

- (void)didTransitionToState:(UITableViewCellStateMask)state

и переместите свой ярлык соответственно.

Должно быть как

- (void)willTransitionToState:(UITableViewCellStateMask)state {

    [super willTransitionToState:state];

    if ((state & UITableViewCellStateShowingDeleteConfirmationMask) == UITableViewCellStateShowingDeleteConfirmationMask) {
       label.frame = ...
    }
}

Редактировать:

- (void)willTransitionToState:(UITableViewCellStateMask)state {

    [super willTransitionToState:state];

//    label.hidden = YES;
//    label.alpha = 0.0;
}

- (void)didTransitionToState:(UITableViewCellStateMask)state {

    [super didTransitionToState:state];

    if (state == UITableViewCellStateShowingDeleteConfirmationMask) {

        [UIView beginAnimations:@"anim" context:nil];
        label.frame = leftFrame;
        [UIView commitAnimations];
    } else if (state == UITableViewCellStateDefaultMask) {

        [UIView beginAnimations:@"anim" context:nil];
        label.frame = rightFrame;
        [UIView commitAnimations];
    }
}

Это взлом, но единственное, что мне помогло, - это скрытое изображение и ограничение его ярлыков.

Например:

У меня была UILabel в UITableViewCell, которая не двигалась вместе с ячейкой, когда я анимировал свою таблицу на экране и за его пределами... но другие ячейки работали просто отлично. Я перепробовал все.

Я закончил тем, что поместил изображение на левой стороне метки (как и в других ячейках) и добавил ограничения от метки к изображению с фиксированной шириной, а также ограничение слева от изображения к контейнеру.

Это исправило мою проблему, и теперь метка анимируется с ячейкой.

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

Другие вопросы по тегам