版權(quán)聲明:未經(jīng)本人允許,禁止轉(zhuǎn)載.
iOS 7之后,tableView的分割線左邊距默認(rèn)設(shè)置為15,如圖
左間距15的分割線.png
iOS 7 添加屬性separatorInset,設(shè)置為UIEdgeInsetsZero即可左對(duì)齊
iOS 8之后,由于view添加屬性layoutMargins,所以需要兩個(gè)屬性都設(shè)置為 UIEdgeInsetsZero
1.代碼設(shè)置
- 首先在- viewDidLayoutSubviews方法里設(shè)置tableView的separatorInset和layoutMargins
//OC
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
//設(shè)置separatorInset(iOS7之后)
if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
[self.tableView setSeparatorInset:UIEdgeInsetsZero];
}
//設(shè)置layoutMargins(iOS8之后)
if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
[self.tableView setLayoutMargins:UIEdgeInsetsZero];
}
}
//Swift
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if self.tableView.respondsToSelector(Selector("setSeparatorInset:")) {
self.tableView.separatorInset = UIEdgeInsetsZero
}
if self.tableView.respondsToSelector(Selector("setLayoutMargins:")) {
self.tableView.layoutMargins = UIEdgeInsetsZero
}
} - 在- tableView:willDisplayCell:forRowAtIndexPath:方法(cell將要出現(xiàn))里設(shè)置cell的separatorInset和layoutMargins
//OC
- (void)tableView:(UITableView *)tableView willDisplayCell:(nonnull UITableViewCell *)cell forRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
//設(shè)置separatorInset(iOS7之后)
if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
[cell setSeparatorInset:UIEdgeInsetsZero];
}
//設(shè)置layoutMargins(iOS8之后)
if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
[cell setLayoutMargins:UIEdgeInsetsZero];
}
}
//Swift
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if cell.respondsToSelector(Selector("setSeparatorInset:")) {
cell.separatorInset = UIEdgeInsetsZero
}
if cell.respondsToSelector(Selector("setLayoutMargins:")) {
cell.layoutMargins = UIEdgeInsetsZero
}
}
2.Xib/Storyboard設(shè)置
需要同時(shí)設(shè)置tableView和cell的separatorInset和layoutMargins.(針對(duì)tableView和tableViewController的xib和storyboard不同情況,選擇性設(shè)置即可,最多4個(gè)都設(shè)置)
-
首先設(shè)置TableView的separatorInset,如圖
設(shè)置TableView的SeparatorInset.png
設(shè)置TableView的layoutMargins,如圖
設(shè)置TableView的LayoutMargins.png -
設(shè)置TableViewCell的separatorInset,如圖
設(shè)置Cell的SeparatorInset.png
設(shè)置TableViewCell的layoutMargins,如圖
設(shè)置Cell的LayoutMargins.png