在 UITableViewController 中直接修改 tableView.frame 導致標題欄未同步移動、兩側出現黑邊。
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
// 1. 此時佈局已完成,修改 frame 生效
[self.tableView setFrame:CGRectMake(x, y, width, height)];
// 2. 消除黑邊:設置關鍵窗口背景為白色
[[[UIApplication sharedApplication] keyWindow] setBackgroundColor:[UIColor whiteColor]];
}
viewDidAppear: 視圖層級已就位,修改 frame 不會被後續佈局覆蓋。UITableViewController 的 view 即為 tableView,父視圖為窗口根視圖,窗口背景色透出即為黑邊。@interface CustomTableVC : UIViewController <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@end
@implementation CustomTableVC
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
self.tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
self.tableView.dataSource = self;
self.tableView.delegate = self;
[self.view addSubview:self.tableView];
// 此時可隨意調整 self.tableView.frame,無副作用
}
@end
擺脫 UITableViewController 的諸多隱式約束,靈活性更高。