Programing

iOS 8 UITableView 구분 기호 삽입 0이 작동하지 않음

lottogame 2020. 10. 2. 21:24
반응형

iOS 8 UITableView 구분 기호 삽입 0이 작동하지 않음


UITableView의 구분 기호 삽입이 사용자 정의 값 (오른쪽 0, 왼쪽 )으로 설정된 앱이 0있습니다. 이것은에서 완벽하게 작동 iOS 7.x하지만 iOS 8.0구분 기호 삽입이 15오른쪽 의 기본값으로 설정되어 있음 을 알 수 있습니다. xib 파일에서로 설정 0했지만 여전히 잘못 표시됩니다.

UITableViewCell구분자 여백을 제거하려면 어떻게합니까 ?


iOS 8.0에는 셀 및 테이블보기에 layoutMargins 속성이 도입되었습니다.

이 속성은 iOS 7.0에서 사용할 수 없으므로 할당하기 전에 확인해야합니다!

쉬운 해결 방법은 @ user3570727이 제안한대로 셀을 하위 클래스로 만들고 레이아웃 여백 속성을 재정의하는 것입니다. 그러나 안전 영역에서 여백을 상속하는 것과 같은 시스템 동작이 손실되므로 아래 솔루션을 권장하지 않습니다.

(목표 C)

-(UIEdgeInsets)layoutMargins { 
     return UIEdgeInsetsZero // override any margins inc. safe area
}

(스위프트 4.2) :

override var layoutMargins: UIEdgeInsets { get { return .zero } set { } }

속성을 재정의하지 않거나 조건부로 설정해야하는 경우 계속 읽으십시오.


layoutMargins속성 외에도 Apple은 테이블보기의 여백 설정을 상속하지 못하도록 셀에 속성추가했습니다 . 이 속성을 설정하면 셀에서 테이블보기와 관계없이 자체 여백을 구성 할 수 있습니다. 재정의라고 생각하십시오.

이 속성은라고 preservesSuperviewLayoutMargins하며이를로 설정 NO하면 셀의 layoutMargin설정이 layoutMarginTableView에 설정된 모든 항목을 재정 의 할 수 있습니다. 둘 다 시간을 절약 하고 (테이블 뷰의 설정을 수정할 필요가 없음 ) 더 간결합니다. 자세한 설명은 Mike Abdullah의 답변을 참조하십시오.

참고 : 다음은 Mike Abdullah의 답변에 표현 된 것처럼 셀 수준 여백 설정에 대한 깨끗한 구현입니다 . 셀을 설정하면 preservesSuperviewLayoutMargins=NO테이블보기가 셀 설정을 덮어 쓰지 않습니다. 실제로 전체 테이블보기의 여백이 일관되게하려면 그에 따라 코드를 조정하십시오.

셀 여백 설정 :

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Remove seperator inset
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
           [cell setSeparatorInset:UIEdgeInsetsZero];
    }

    // Prevent the cell from inheriting the Table View's margin settings
    if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        [cell setPreservesSuperviewLayoutMargins:NO];
    }

    // Explictly set your cell's layout margins
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

스위프트 4 :

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    // Remove seperator inset
    if cell.responds(to: #selector(setter: UITableViewCell.separatorInset)) {
        cell.separatorInset = .zero
    }
    // Prevent the cell from inheriting the Table View's margin settings
    if cell.responds(to: #selector(setter: UITableViewCell.preservesSuperviewLayoutMargins)) {
        cell.preservesSuperviewLayoutMargins = false
    }
    // Explictly set your cell's layout margins
    if cell.responds(to: #selector(setter: UITableViewCell.layoutMargins)) {
        cell.layoutMargins = .zero
    }
}

설정 preservesSuperviewLayoutMarginsNO로 셀 재산은 해야 휴대 여백을 무시에서 테이블보기를 방지합니다. 어떤 경우에는 제대로 작동하지 않는 것 같습니다.

모두 실패하면 테이블 뷰 여백을 무차별 대입 할 수 있습니다.

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];

    // Force your tableview margins (this may be a bad idea)
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }

    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
} 

스위프트 4 :

func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    // Force your tableview margins (this may be a bad idea)
    if tableView.responds(to: #selector(setter: UITableView.separatorInset)) {
        tableView.separatorInset = .zero
    }
    if tableView.responds(to: #selector(setter: UITableView.layoutMargins)) {
        tableView.layoutMargins = .zero
    }
}

... 그리고 당신은 간다! 이것은 iOS 7 및 8에서 작동합니다.


편집 : 모하메드 살레 내 관심을 아이폰 OS 9에서의 가능한 변화를 가져왔다 당신은 테이블보기의 설정해야 할 수도 있습니다 cellLayoutMarginsFollowReadableWidthNO당신이 세트 또는 여백을 사용자 정의하려는 경우입니다. 귀하의 마일리지는 다를 수 있으며 이는 잘 문서화되지 않았습니다.

이 속성은 iOS 9에만 존재하므로 설정하기 전에 확인하십시오.

if([myTableView respondsToSelector:@selector(setCellLayoutMarginsFollowReadableWidth:)])
{
    myTableView.cellLayoutMarginsFollowReadableWidth = NO;
} 

스위프트 4 :

if myTableView.responds(to: #selector(setter: self.cellLayoutMarginsFollowReadableWidth)) {
    myTableView.cellLayoutMarginsFollowReadableWidth = false
}

( iOS 8 UITableView 구분 기호 삽입 0의 코드 위가 작동하지 않음 )

편집 : 다음은 순수한 인터페이스 빌더 접근 방식입니다.

TableViewAttributesInspector TableViewCellSizeInspector

참고 : iOS 11은이 동작의 대부분을 변경하고 단순화하며 업데이트가 곧있을 예정입니다.


Arg !!! Cell하위 클래스 에서이 작업을 수행 한 후 :

- (UIEdgeInsets)layoutMargins
{
    return UIEdgeInsetsZero;
}

또는 cell.layoutMargins = UIEdgeInsetsZero;나를 위해 고정 설정 .


문제를 해결하기 위해 맹목적으로 돌격하기 전에 문제를 이해하는 데 잠시 시간을 할애합시다.

디버거를 빠르게 살펴보면 구분선이 UITableViewCell. 셀 자체가 이러한 선의 레이아웃에 대해 상당한 책임을지는 것 같습니다.

iOS 8에는 레이아웃 여백 개념이 도입되었습니다 . 기본적으로보기의 레이아웃 여백은 8pt모든면에 있으며 상위보기에서 상속 됩니다.

가장 잘 알 수 있듯이, 구분선을 배치 할 때 UITableViewCell왼쪽 레이아웃 여백을 고려하여 왼쪽 삽입을 제한하는 데 사용합니다.

이 모든 것을 합치면 원하는 인세 트를 진정으로 0으로 만들려면 다음을 수행해야합니다.

  • 왼쪽 레이아웃 여백을 0
  • 이를 재정의하는 상속 된 여백을 중지합니다.

이렇게 말하면 달성하는 것은 매우 간단한 작업입니다.

cell.layoutMargins = UIEdgeInsetsZero;
cell.preservesSuperviewLayoutMargins = NO;

참고할 사항 :

  • 이 코드는 필요 셀당 (방금 결국 셀의 속성을 구성하고) 일단 실행하고, 아무것도 특별한 당신이 그것을 실행하도록 선택하면에 대해이있다. 당신에게 가장 깨끗한 일을하십시오.
  • 안타깝게도 Interface Builder에서 구성 할 수있는 속성은 없지만 preservesSuperviewLayoutMargins원하는 경우 사용자 정의 런타임 속성을 지정할 수 있습니다 .
  • 분명히 앱이 이전 OS 릴리스를 대상으로하는 경우 iOS 8 이상에서 실행될 때까지 위 코드를 실행하지 않아야합니다.
  • 을 설정하는 대신 왼쪽 여백 을 갖도록 상위 뷰 (예 : 테이블)를 구성 preservesSuperviewLayoutMargins0 있지만 전체 계층 구조를 제어하지 않기 때문에 본질적으로 오류가 발생하기 쉽습니다.
  • 왼쪽 여백 만 설정 0하고 나머지는 그대로 두는 것이 약간 더 깔끔 할 것입니다 .
  • UITableView일반 스타일 테이블의 맨 아래에 그려지는 "추가"구분 기호에 0 인셋을 넣으려면 테이블 수준에서도 동일한 설정을 지정해야한다고 생각합니다 (이것도 시도하지 않았습니다!).

나는 이것이 내가 여기에서 묻는 것과 동일한 질문이라고 생각 합니다 .XCode 6 iPhone 시뮬레이터 용 iOS 8 UITableView에서 SeparatorInset 제거

에서 아이폰 OS 8 에서 상속하는 모든 객체에 대한 하나 개의 새로운 특성이있다 UIView. 따라서 SeparatorInsetiOS 7.x에서 설정하는 솔루션 은 iOS 8의 UITableView에 표시되는 공백을 제거 할 수 없습니다.

새 속성은 " layoutMargins "입니다.

@property(nonatomic) UIEdgeInsets layoutMargins
Description   The default spacing to use when laying out content in the view.
Availability  iOS (8.0 and later)
Declared In   UIView.h
Reference UIView Class Reference

iOS 8 UITableView setSeparatorInset : UIEdgeInsetsZero setLayoutMargins : UIEdgeInsetsZero

해결책:-

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{

    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }

    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }

   if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
   }
}

존재 cell.layoutMargins = UIEdgeInsetsZero;여부를 확인하지 않고 설정 하면 layoutMarginsiOS 7.x에서 앱이 충돌합니다. (가) 경우에 따라서, 가장 좋은 방법은 검사 될 것 layoutMargins전에 먼저 존재한다 setLayoutMargins:UIEdgeInsetsZero.


애플리케이션 시작시 (UI가로드되기 전) UIAppearance를 한 번 사용하여 기본 전역 설정으로 설정할 수 있습니다.

// iOS 7:
[[UITableView appearance] setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
[[UITableView appearance] setSeparatorInset:UIEdgeInsetsZero];

[[UITableViewCell appearance] setSeparatorInset:UIEdgeInsetsZero];

// iOS 8:
if ([UITableView instancesRespondToSelector:@selector(setLayoutMargins:)]) {

    [[UITableView appearance] setLayoutMargins:UIEdgeInsetsZero];
    [[UITableViewCell appearance] setLayoutMargins:UIEdgeInsetsZero];
    [[UITableViewCell appearance] setPreservesSuperviewLayoutMargins:NO];

}

이렇게하면 UIViewController의 코드를 깨끗하게 유지하고 원하는 경우 언제든지 재정의 할 수 있습니다.


iOS는 셀 및 테이블보기에 layoutMargins 속성을 도입했습니다.

이 속성은 iOS 7.0에서 사용할 수 없으므로 할당하기 전에 확인해야합니다!

그러나 Apple은 테이블 뷰의 여백 설정을 상속하지 못하게하는 preservesSuperviewLayoutMargins 라는 속성 을 셀에 추가했습니다 . 이렇게하면 셀이 테이블보기와 관계없이 자체 여백을 구성 할 수 있습니다. 재정의라고 생각하십시오.

이 속성은 preservesSuperviewLayoutMargins 라고 하며 NO로 설정하면 테이블 뷰의 layoutMargin 설정을 자신의 셀의 layoutMargin 설정으로 재정의 할 수 있습니다. 둘 다 시간을 절약 하고 (테이블 뷰의 설정을 수정할 필요가 없음 ) 더 간결합니다. 자세한 설명은 Mike Abdullah의 답변을 참조하십시오.

참고 : 이것은 Mike Abdullah의 답변에 표현 된 것처럼 적절하고 덜 지저분한 구현입니다. 셀의 preservesSuperviewLayoutMargins = NO를 설정하면 테이블보기가 셀 설정을 무시하지 않습니다.

첫 번째 단계-셀 여백 설정 :

/*
    Tells the delegate that the table view is about to draw a cell for a particular row.
*/
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell,
    forRowAtIndexPath indexPath: NSIndexPath)
{
    // Remove separator inset
    if cell.respondsToSelector("setSeparatorInset:") {
        cell.separatorInset = UIEdgeInsetsZero
    }

    // Prevent the cell from inheriting the Table View's margin settings
    if cell.respondsToSelector("setPreservesSuperviewLayoutMargins:") {
        cell.preservesSuperviewLayoutMargins = false
    }

    // Explictly set your cell's layout margins
    if cell.respondsToSelector("setLayoutMargins:") {
        cell.layoutMargins = UIEdgeInsetsZero
    }
}

NO로 세포에 preservesSuperviewLayoutMargins 속성을 설정 해야 휴대 여백을 무시에서 테이블보기를 방지합니다. 어떤 경우에는 제대로 작동하지 않는 것 같습니다.

두 번째 단계-모든 것이 실패하는 경우에만 테이블 뷰 여백을 무차별 대입 할 수 있습니다.

/*
    Called to notify the view controller that its view has just laid out its subviews.
*/
override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    // Force your tableview margins (this may be a bad idea)
    if self.tableView.respondsToSelector("setSeparatorInset:") {
        self.tableView.separatorInset = UIEdgeInsetsZero
    }

    if self.tableView.respondsToSelector("setLayoutMargins:") {
        self.tableView.layoutMargins = UIEdgeInsetsZero
    }
}

... 그리고 당신은 간다! 이것은 iOS 8과 iOS 7에서 작동합니다.

참고 : iOS 8.1 및 7.1을 사용하여 테스트했으며 제 경우에는이 설명의 첫 번째 단계 만 사용하면되었습니다.

두 번째 단계는 렌더링 된 셀 아래에 셀이 채워지지 않은 경우에만 필요합니다. 테이블이 테이블 모델의 행 수보다 큰 경우. 두 번째 단계를 수행하지 않으면 다른 구분 기호 오프셋이 발생합니다.


Swift에서는 layoutMargins속성 이기 때문에 약간 더 성가 시므로 getter setter 를 재정의해야합니다 .

override var layoutMargins: UIEdgeInsets {
  get { return UIEdgeInsetsZero }
  set(newVal) {}
}

이것은 효과적으로 layoutMargins읽기 전용으로 만들 것이며 , 제 경우에는 괜찮습니다.


iOS 9의 경우 다음을 추가해야합니다.

if([myTableView respondsToSelector:@selector(setCellLayoutMarginsFollowReadableWidth:)])
{
    myTableView.cellLayoutMarginsFollowReadableWidth = NO;
} 

자세한 내용은 질문을 참조하십시오 .


Swift 2.0 확장

tableview 셀 구분 기호에서 여백을 제거하기 위해 만든 확장을 공유하고 싶었습니다.

extension UITableViewCell {
    func removeMargins() {

        if self.respondsToSelector("setSeparatorInset:") {
            self.separatorInset = UIEdgeInsetsZero
        }

        if self.respondsToSelector("setPreservesSuperviewLayoutMargins:") {
            self.preservesSuperviewLayoutMargins = false
        }

        if self.respondsToSelector("setLayoutMargins:") {
            self.layoutMargins = UIEdgeInsetsZero
        }
    }
}

문맥에서 사용 :

    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CustomCell

    cell.removeMargins()
    return cell

빠른:

override func viewDidLoad() {
    super.viewDidLoad()

    if self.tableView.respondsToSelector("setSeparatorInset:") {
        self.tableView.separatorInset = UIEdgeInsetsZero
    }
    if self.tableView.respondsToSelector("setLayoutMargins:") {
        self.tableView.layoutMargins = UIEdgeInsetsZero
    }

    self.tableView.layoutIfNeeded()            // <--- this do the magic
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
     ...

    if cell.respondsToSelector("setSeparatorInset:") {
        cell.separatorInset = UIEdgeInsetsZero
    }
    if cell.respondsToSelector("setLayoutMargins:") {
        cell.layoutMargins = UIEdgeInsetsZero
    }

    return cell
}

나는 이것을 수행하여 작동시켰다.

tableView.separatorInset = UIEdgeInsetsZero;
tableView.layoutMargins = UIEdgeInsetsZero;
cell.layoutMargins = UIEdgeInsetsZero;

테이블 뷰 대신 cdstamper가 제안한 것에 관해서는 셀의 layoutSubview 메서드에 아래 줄을 추가하면 효과적입니다.

- (void)layoutSubviews 
{
    [super layoutSubviews];

    if ([self respondsToSelector:@selector(setSeparatorInset:)])
                [self setSeparatorInset:UIEdgeInsetsZero];

        if ([self respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)])
        {
            [self setPreservesSuperviewLayoutMargins:NO];;
        }

        if ([self respondsToSelector:@selector(setLayoutMargins:)]) 
        {
            [self setLayoutMargins:UIEdgeInsetsZero];
        }
}

Swift 3.0 예제 :

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    // removing seperator inset
    if cell.responds(to: #selector(setter: UITableViewCell.separatorInset)) {
        cell.separatorInset = .zero
    }
    // prevent the cell from inheriting the tableView's margin settings
    if cell.responds(to: #selector(setter: UIView.preservesSuperviewLayoutMargins)) {
        cell.preservesSuperviewLayoutMargins = false
    }
    // explicitly setting cell's layout margins
    if cell.responds(to: #selector(setter: UITableViewCell.layoutMargins)) {
        cell.layoutMargins = .zero
    }
}

많은 조사 끝에 ...

이 물건을 완전히 제어 할 수있는 유일한 방법이 있습니다.

각 셀의 구분자 삽입 및 레이아웃 여백을 완전히 제어합니다. 에서이 작업을 수행 willDisplayCell온 방법 UITableviewDelegate.

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    cell.layoutMargins = UIEdgeInsetsZero
    cell.contentView.layoutMargins = UIEdgeInsetsMake(0, 10, 0, 10)
    cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)
}

셀 개체는 구분 기호를 제어하고 contentView나머지는 모두 제어합니다. 구분 기호 삽입 공간이 예상치 못한 색상으로 표시되는 경우이 문제를 해결할 수 있습니다.

cell.backgroundColor = cell.contentView.backgroundColor

간단한 솔루션 스위프트 에 대한 아이폰 OS 8 사용자 정의와UITableViewCell

override func awakeFromNib() {
    super.awakeFromNib()

    self.layoutMargins = UIEdgeInsetsZero
    self.separatorInset = UIEdgeInsetsZero
}

이런 식으로 위의 대부분의 답변에서 알 수 있듯이 각각에 대해 설정 layoutMargin하고 separatorInset한 번만 수행합니다 willDisplayCell.

사용자 지정을 사용하는 경우 UITableViewCell올바른 위치입니다. 그렇지 않으면 tableView:cellForRowAtIndexPath.

또 다른 힌트 : preservesSuperviewLayoutMargins = false기본값이 이미 있으므로 설정할 필요가 없습니다 NO!


나를 위해 간단한 라인이 일을했습니다.

cell.layoutMargins = UIEdgeInsetsZero

아래 코드를 추가하면이 프로그램을 해결할 수 있습니다.

행운을 빕니다!

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {

       if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
           [cell setSeparatorInset:UIEdgeInsetsZero];
       }

       if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
           [cell setLayoutMargins:UIEdgeInsetsZero];
       }

}

Swift의 Lukasz 답변 :

    // iOS 7:
    UITableView.appearance().separatorStyle = .SingleLine
    UITableView.appearance().separatorInset = UIEdgeInsetsZero
    UITableViewCell.appearance().separatorInset = UIEdgeInsetsZero

    // iOS 8:
    if UITableView.instancesRespondToSelector("setLayoutMargins:") {
        UITableView.appearance().layoutMargins = UIEdgeInsetsZero
        UITableViewCell.appearance().layoutMargins = UIEdgeInsetsZero
        UITableViewCell.appearance().preservesSuperviewLayoutMargins = false
    }

이것은 Swift에서 나를 위해 일하는 코드입니다.

override func viewDidLoad() 
{
    super.viewDidLoad()
    ...
    if tableView.respondsToSelector("setSeparatorInset:") {
        tableView.separatorInset = UIEdgeInsetsZero
    }
}

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell,forRowAtIndexPath indexPath: NSIndexPath)
{
    if cell.respondsToSelector("setSeparatorInset:") {
        cell.separatorInset.left = CGFloat(0.0)
    }
    if tableView.respondsToSelector("setLayoutMargins:") {
        tableView.layoutMargins = UIEdgeInsetsZero
    }
    if cell.respondsToSelector("setLayoutMargins:") {
        cell.layoutMargins.left = CGFloat(0.0)
    }
}

모든 셀 / tableView 가장자리 / 여백 조정이 tableView:willDisplayCell:forRowAtIndexPath:불필요한 코드를 .NET Framework에 넣지 않고 메서드 에서 수행되기 때문에 이것은 나에게 가장 깨끗해 보입니다 tableView:cellForRowAtIndexPath:.

Btw, 저는 셀의 왼쪽 separatorInset / layoutMargins 만 설정하고 있습니다.이 경우 셀에 설정 한 제약 조건을 망치고 싶지 않기 때문입니다.

Swift 2.2로 업데이트 된 코드 :

 override func viewDidLoad() {
   super.viewDidLoad()       

    if tableView.respondsToSelector(Selector("setSeparatorInset:")) {
      tableView.separatorInset = UIEdgeInsetsZero
        }
    }

 override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell,forRowAtIndexPath indexPath: NSIndexPath) {
        if cell.respondsToSelector(Selector("setSeparatorInset:")) {
            cell.separatorInset.left = CGFloat(0.0)
        }
        if tableView.respondsToSelector(Selector("setLayoutMargins:")) {
            tableView.layoutMargins = UIEdgeInsetsZero
        }
        if cell.respondsToSelector(Selector("setLayoutMargins:")) {
            cell.layoutMargins.left = CGFloat(0.0)
        }
    }

대부분의 답변은 분리 세트를 보이고있다 및 레이아웃 여백 방법 (즉, 다양한 이상으로 설정되고 viewDidLayoutSubviews, willDisplayCell세포와 tableviews에 대한, 등),하지만 난 그냥이 퍼팅 것으로 나타났습니다 cellForRowAtIndexPath훌륭한 작품. 가장 깨끗한 방법 인 것 같습니다.

// kill insets for iOS 8
if ([[UIDevice currentDevice].systemVersion floatValue] >= 8) {
    cell.preservesSuperviewLayoutMargins = NO;
    [cell setLayoutMargins:UIEdgeInsetsZero];
}
// iOS 7 and later
if ([cell respondsToSelector:@selector(setSeparatorInset:)])
    [cell setSeparatorInset:UIEdgeInsetsZero];

아래 코드 스 니펫을 사용하면 IOS 8 및 7에서 UITableView에 대한 원치 않는 패딩 문제를 방지 할 수 있습니다.

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{

    if ([tableView respondsToSelector:@selector(setSeparatorInset:)])
    {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }

    if ([tableView respondsToSelector:@selector(setLayoutMargins:)])
    {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }

    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

대신 업데이트 preservesSuperviewLayoutMarginslayoutMargins모든 시간 (사용의 셀 스크롤 willDisplayCell), I는 한 번 그것을 할 게 좋을 것 cellForRowAtIndexPath::

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath)

    cell.preservesSuperviewLayoutMargins = false
    cell.layoutMargins = UIEdgeInsetsZero

    return cell

}

iOS8에서 :

내 UITableViewCell 하위 클래스에 추가 :

- (UIEdgeInsets)layoutMargins {
    return UIEdgeInsetsZero;
}

그리고 이것은 "tableView : cellForRowAtIndexPath"또는 "tableView : willDisplayCell"에 :

[editCell setSeparatorInset:UIEdgeInsetsZero];

나를 위해 일했습니다.


다음은 삽입물을 전체적으로 제거하는 쉬운 방법입니다.

에서 UITableViewCell+Extensions.swift:

import UIKit

extension UITableViewCell {

  override public var layoutMargins: UIEdgeInsets {
    get { return UIEdgeInsetsZero }
    set { }
  }

}

에서 AppDelegate application:didFinishLaunchingWithOptions::

  UITableViewCell.appearance().separatorInset = UIEdgeInsetsZero

separatorInseta) 확장 프로그램에서 재정의 하거나 b) layoutMargins대신에 대한 모양 프록시를 설정하는 것으로 생각할 수 있습니다 . 둘 다 작동하지 않습니다. separatorInset속성으로 표시 되더라도 속성 (또는 메서드)으로 재정의하려고하면 컴파일러 오류가 발생합니다. 그리고의 외관 프록시 설정 UITableViewCelllayoutMargins(도에 대한 외관 프록시를 설정하거나, 그 문제에 대한을 UITableView의 ' layoutMarginsseparatorInset) 아무 효과가 없습니다.


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        // ... Get the cell
        cell.separatorInset = UIEdgeInsetsMake(0.f, 20.f, 0.f, [UIScreen mainScreen].bounds.size.width - 20);
        // others
        return cell;
}

특정 셀에 대해 구분 기호를 숨기려는 경우.


3 층에서 답을 본 후 TableView와 TableViewCell 사이의 구분자 설정 관계를 파악하고 몇 가지 테스트를했습니다. 내 결론은 다음과 같습니다.

  1. 셀의 구분 기호를 0으로 설정하려면 구분 기호를 두 단계로 이동해야한다고 생각할 수 있습니다. 첫 번째 단계는 셀의 구분 기호 를 0으로 설정하는 것입니다. 두 번째 단계는 셀의 marginlayout 을 0 으로 설정하는 것 입니다.

  2. TableView의 separatorinsetmarginlayout 설정은 Cell의 separatorinset에 영향을 줄 수 있습니다 . 그러나 테스트에서 TableView의 separatorinset 이 쓸모없는 것 같고 TableView의 marginlayout 이 실제로 셀의 marginlayout에 영향을 줄 수 있음을 알았습니다 .

  3. 셀의 PreservesSuperviewLayoutMargins = false로 설정하면 셀에 대한 TableView의 marginlayout 효과를 차단할 수 있습니다 .

  4. 솔루션 중 하나 :

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = UITableViewCell()
    
        cell.preservesSuperviewLayoutMargins = false
        cell.separatorInset = UIEdgeInsetsZero
        cell.layoutMargins = UIEdgeInsetsZero
    
        return cell
    }
    

이것이 내 해결책입니다. 이것은 사용자 정의 셀 하위 클래스에 적용되며 둘 다 하위 클래스에 추가하기 만하면됩니다.

  1. - (UIEdgeInsets)layoutMargins {    
        return UIEdgeInsetsMake(0, 10, 0, 10);
    }
    

2.

self.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10);

그리고 디자이너에게 직접 그려달라고 요청하지 않고도 구분자의 위치를 ​​사용자 지정할 수있어 편리합니다 ..........


가장 많이 득표 한 답변보다 더 간결한 방식으로 ...

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {

    if ([cell respondsToSelector:@selector(setSeparatorInset:)] && [cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)] && [cell respondsToSelector:@selector(setLayoutMargins:)]) {
         [cell setSeparatorInset:UIEdgeInsetsZero];
         [cell setPreservesSuperviewLayoutMargins:NO];
         [cell setLayoutMargins:UIEdgeInsetsZero];
    }

}


이 스 니펫을 추가하면 Swift에서 간단하고 우아하게 iOS8에서 작동합니다. :)

    // tableview single line
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    cell.preservesSuperviewLayoutMargins = false
    cell.layoutMargins = UIEdgeInsetsZero
}

이것은 iOS 8 및 iOS 9에서 완벽하게 작동했습니다.

대한 OBJ-C

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  { 
        if ([tableView respondsToSelector:@selector(setSeparatorInset:)])
        {
            [tableView setSeparatorInset:UIEdgeInsetsZero];
        }

        if ([tableView respondsToSelector:@selector(setLayoutMargins:)])
        {
            [tableView setLayoutMargins:UIEdgeInsetsZero];
        }

        if ([cell respondsToSelector:@selector(setLayoutMargins:)])
        {
            [cell setLayoutMargins:UIEdgeInsetsZero];
        }
         return cell;
    }

참고 URL : https://stackoverflow.com/questions/25770119/ios-8-uitableview-separator-inset-0-not-working

반응형