重寫 layoutSubviews 修改 textLabel.frame 會破壞 Cell 內部佈局邏輯,導致分割線消失、約束衝突。
@interface CustomCell : UITableViewCell
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *actionButton;
@end
@implementation CustomCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// 1. 標題標籤
_titleLabel = [[UILabel alloc] init];
_titleLabel.font = [UIFont systemFontOfSize:14];
_titleLabel.textColor = [UIColor darkGrayColor];
_titleLabel.numberOfLines = 0;
[self.contentView addSubview:_titleLabel];
// 2. 操作按鈕
_actionButton = [UIButton buttonWithType:UIButtonTypeSystem];
[_actionButton setTitle:@"操作" forState:UIControlStateNormal];
[self.contentView addSubview:_actionButton];
}
return self;
}
- (void)layoutSubviews {
[super layoutSubviews]; // 必須調用
CGFloat padding = 15;
CGFloat btnWidth = 80;
CGFloat btnHeight = 30;
// 按鈕靠右
_actionButton.frame = CGRectMake(
self.bounds.size.width - padding - btnWidth,
(self.bounds.size.height - btnHeight) / 2,
btnWidth, btnHeight
);
// 標籤佔據剩餘空間,避開按鈕
_titleLabel.frame = CGRectMake(
padding, padding,
_actionButton.frame.origin.x - padding * 2,
self.bounds.size.height - padding * 2
);
}
@end
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCell"];
cell.titleLabel.text = dataArray[indexPath.row];
[cell.actionButton addTarget:self action:@selector(btnTap:) forControlEvents:UIControlEventTouchUpInside];
cell.actionButton.tag = indexPath.row;
return cell;
}
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
// ... 創建視圖 ...
_titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
_actionButton.translatesAutoresizingMaskIntoConstraints = NO;
[self.contentView addConstraints:@[
[_actionButton.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-15],
[_actionButton.centerYAnchor constraintEqualToAnchor:self.contentView.centerYAnchor],
[_actionButton.widthAnchor constraintEqualToConstant:80],
[_titleLabel.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:15],
[_titleLabel.trailingAnchor constraintEqualToAnchor:_actionButton.leadingAnchor constant:-10],
[_titleLabel.topAnchor constraintEqualToAnchor:self.contentView.topAnchor constant:10],
[_titleLabel.bottomAnchor constraintEqualToAnchor:self.contentView.bottomAnchor constant:-10]
]];
}