Prevent indentation of UITableViewCell (contentView) while editing

前端 未结 9 805
心在旅途
心在旅途 2020-12-05 02:38

Is it possible to keep the contentView.frame always the same, regardless of tableView.editing? I already tried to override layoutSubviews

9条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-05 03:04

    Luckily, iOS is perfectly equipped to keep whatever value constant.

    This (ugly) piece of code will keep the frame fixed to whatever value has origin.x==0. This is easily adapted to your particular needs.

    // put this in your UITableViewCell subclass
    -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
    {
        NSLog(@"observed value for kp %@ changed: %@",keyPath,change);
        if ( [keyPath isEqual:@"frame"] && object == self.contentView )
        {
            CGRect newFrame = self.contentView.frame;
            CGRect oldFrame = [[change objectForKey:NSKeyValueChangeOldKey] CGRectValue];
            NSLog(@"frame old: %@  new: %@",NSStringFromCGRect(oldFrame),NSStringFromCGRect(newFrame));
    
            if ( newFrame.origin.x != 0 ) self.contentView.frame = oldFrame;
        }
    }
    
    // add the cell as an observer for frame changes, somewhere in initialization:
    [self.contentView addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionOld context:nil];
    
    // IMPORTANT: remove the cell as an observer in -dealloc:
    [self.contentView removeObserver:self forKeyPath:@"frame"];
    

    This will only allow the frame to change to values with an origin.x==0. Remove the NSLog() lines for Release builds.

    I have tested this for a few minutes and haven't seen any side effect.

提交回复
热议问题