- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
}
// 關鍵:在佈局完成後修改 frame
[cell layoutIfNeeded]; // 確保 textLabel 已佈局
CGRect labelFrame = cell.textLabel.frame;
labelFrame.origin.x += 20; // 向右偏移 20pt
labelFrame.size.width -= 20; // 寬度相應縮減,防止文字截斷
cell.textLabel.frame = labelFrame;
cell.textLabel.text = @"示例文字";
return cell;
}
⚠️ 注意:iOS 13+ 若使用 UIListContentConfiguration,需改用 cell.contentConfiguration 設定 textProperties 的 directionalLayoutMargins。
// CustomCell.h
@interface CustomCell : UITableViewCell
@property (nonatomic, strong) UILabel *customLabel;
@end
// CustomCell.m
@implementation CustomCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
_customLabel = [[UILabel alloc] init];
_customLabel.translatesAutoresizingMaskIntoConstraints = NO;
[self.contentView addSubview:_customLabel];
// 設定約束:左邊距 20,上下居中,右邊距 15
[NSLayoutConstraint activateConstraints:@[
[_customLabel.leadingAnchor constraintEqualToAnchor:self.contentView.leadingAnchor constant:20],
[_customLabel.centerYAnchor constraintEqualToAnchor:self.contentView.centerYAnchor],
[_customLabel.trailingAnchor constraintEqualToAnchor:self.contentView.trailingAnchor constant:-15]
]];
}
return self;
}
@end
// 使用
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCell"];
if (!cell) cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CustomCell"];
cell.customLabel.text = @"自訂偏移文字";
return cell;
}
| 場景 | 推薦方式 |
|---|---|
| 僅需微調偏移、專案簡單、無複雜佈局 | 方式一:調整 textLabel frame |
| 需自訂字型、顏色、多行、圖文混排、支援動態型別 | 方式二:自訂 Cell + Auto Layout |
| iOS 14+ 採用 UICollectionView/ListContentConfiguration | 使用 UIListContentConfiguration 設定 textProperties.directionalLayoutMargins |
class CustomCell: UITableViewCell {
let customLabel = UILabel()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
customLabel.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(customLabel)
NSLayoutConstraint.activate([
customLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 20),
customLabel.centerYAnchor.constraint(equalTo: contentView.centerAnchor),
customLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -15)
])
}
required init?(coder: NSCoder) { fatalError() }
}
自訂 Cell 雖初期代碼較多,但將佈局邏輯封裝於 Cell 內部,符合單一職責原則,長期維護成本最低。