选择单元格后,表格单元格内容(标题)向左移动

在此处输入图像描述

在tableview单元格中,我将单元格标题文本对齐设置为中心,工作正常,但选择单元格后,标题左对齐。 此问题仅适用于iOS 7.0。

编辑:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { BaseListCell *cell = [self.listTableView dequeueReusableCellWithIdentifier:listCellIdentifier forIndexPath:indexPath]; cell.textLabel.text = _listArray[indexPath.row]; cell.textLabel.userInteractionEnabled = NO; return cell; } 

在BaseListCell.m中

 - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { self = [super initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier]; if (self) { self.textLabel.textColor =[UIColor grayColor]; self.textLabel.textAlignment = NSTextAlignmentCenter; self.textLabel.font = [UIFont mediumFontWithSize:16.f]; self.textLabel.translatesAutoresizingMaskIntoConstraints = NO; NSLayoutConstraint *labelHCN = [NSLayoutConstraint constraintWithItem:self.textLabel attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeCenterX multiplier:1.f constant:0]; [self.contentView addConstraint:labelHCN]; NSLayoutConstraint *labelVCN = [NSLayoutConstraint constraintWithItem:self.textLabel attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeCenterY multiplier:1.f constant:0]; [self.contentView addConstraint:labelVCN]; } return self; } 

这是因为您没有正确设置自动布局。 你有没有解决问题? 为什么你真的需要以下

 self.textLabel.translatesAutoresizingMaskIntoConstraints = NO; NSLayoutConstraint *labelHCN = [NSLayoutConstraint constraintWithItem:self.textLabel attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeCenterX multiplier:1.f constant:0]; [self.contentView addConstraint:labelHCN]; NSLayoutConstraint *labelVCN = [NSLayoutConstraint constraintWithItem:self.textLabel attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeCenterY multiplier:1.f constant:0]; [self.contentView addConstraint:labelVCN]; 

我因为这段代码而遇到麻烦。 你可以尝试排除它

您最好将文本字段声明如下

在BaseListCell.m中

 - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { self = [super initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier]; if (self) { } return self; } - (void)awakeFromNib { self.textLabel.textColor =[UIColor grayColor] self.textLabel.textAlignment = NSTextAlignmentCenter; self.textLabel.font = [UIFont mediumFontWithSize:16.f]; } 

首先启用使用自动布局使用大小类如下所示在表视图和表视图单元格中首先执行此操作。并告诉我您的问题

在此处输入图像描述

如果要将文本vew或标签等放置在表视图的右侧,请单击它的引脚。 在此处输入图像描述

然后选择约束left,right,top和only height。 在此处输入图像描述

点击添加4个约束 在此处输入图像描述

你也可以检查一下:

iOS – 自定义表格单元格不是UITableView的全宽度