Program Tip

iPhone에서 TableView 구분 기호를 사용자 지정하는 방법

programtip 2020. 11. 19. 21:56
반응형

iPhone에서 TableView 구분 기호를 사용자 지정하는 방법


기본적으로 uitableview에는 한 줄 구분 기호가 있습니다.

하지만 맞춤 라인을 구분 기호로 사용하고 싶습니다.

가능합니까? 어떻게?


UITableViewseparatorColor 속성을 사용하여 구분 기호의 색상을 변경하는 것 이상의 작업을 수행 하려면 separatorStyle 속성을 UITableViewCellSeparatorStyleNone으로 설정 한 다음 다음 중 하나 를 수행 할 수 있습니다.

  • 사용자 지정 구분자를 포함하는 사용자 지정 UITableViewCell을 만듭니다.
  • 사용자 지정 구분 기호를 포함하는 대체 [UITableViewCell] [6]을 만듭니다.

예를 들어, 테이블에 현재 5 개의 행이 표시되는 경우 9 개 행을 표시하도록 업데이트 할 수 있으며 인덱스 1, 3, 5, 7의 행은 구분 셀이됩니다.


더 나은 해결책은 셀의 현재 너비와 높이를 사용하는 것입니다. 이 같은:

UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, cell.contentView.frame.size.height - 1.0, cell.contentView.frame.size.width, 1)];

lineView.backgroundColor = [UIColor darkGrayColor];
[cell.contentView addSubview:lineView];

다른 행에 대해 다른 구분자 색상이 필요하거나 탭에서 행이 강조 표시 될 때 구분자가 계속 표시되도록하려면 다음을 시도하십시오.

self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

// We have to use the borderColor/Width as opposed to just setting the 
// backgroundColor else the view becomes transparent and disappears during 
// the cell's selected/highlighted animation
UIView *separatorView = [[UIView alloc] initWithFrame:CGRectMake(0, 43, 1024, 1)];
separatorView.layer.borderColor = [UIColor redColor].CGColor;
separatorView.layer.borderWidth = 1.0;
[cell.contentView addSubview:separatorView];

이것은 셀의 배경색이 투명하다고 가정합니다.


위의 솔루션은 광범위한 실험에서 나왔습니다. 사람들에게 도움이 될 것이라고 확신하는 내 발견에 대한 몇 가지 메모는 다음과 같습니다.

정상적인 "선택되지 않음"상태

  • contentView (별도로 코딩하지 않는 한 XIB에있는 것)는 정상적으로 그려집니다.
  • selectedBackgroundView가 숨겨져 있습니다.
  • backgroundView가 표시됩니다 (따라서 contentView가 투명하면 backgroundView가 표시되거나 backgroundView를 정의하지 않은 경우 UITableView 자체의 배경색이 표시됩니다).

셀이 선택되면 애니메이션없이 다음이 즉시 발생합니다.

  • contentView 내의 모든 뷰 / 하위 뷰는 backgroundColor가 지워지고 (또는 투명으로 설정 됨) 레이블 등 텍스트 색상이 선택한 색상으로 변경됩니다.
  • selectedBackgroundView가 표시됩니다 (이보기는 항상 셀의 전체 크기입니다 (사용자 정의 프레임은 무시되고 필요한 경우 하위보기 사용). 또한 하위보기의 backgroundColor는 어떤 이유로 표시되지 않습니다. 투명하게 설정되었을 수 있습니다. contentView처럼). selectedBackgroundView를 정의하지 않은 경우 Cocoa는 파란색 (또는 회색) 그라데이션 배경을 생성 / 삽입하고이를 표시합니다)
  • backgroundView는 변경되지 않았습니다.

셀을 선택 취소하면 강조 표시를 제거하는 애니메이션이 시작됩니다.

  • selectedBackgroundView 알파 속성은 1.0 (완전 불투명)에서 0.0 (완전 투명)까지 애니메이션됩니다.
  • backgroundView는 다시 변경되지 않습니다 (따라서 애니메이션은 selectedBackgroundView와 backgroundView 사이의 크로스 페이드처럼 보입니다)
  • 애니메이션이 완료되면 contentView가 "선택되지 않음"상태로 다시 그려지고 하위 뷰 backgroundColor가 다시 표시됩니다 (이로 인해 애니메이션이 끔찍하게 보일 수 있으므로 UIView.backgroundColor를 사용하지 않는 것이 좋습니다. contentView)

이러한 답변으로 인해 셀에 추가 한 구분 기호가 강조 사각형을 덮어 씁니다 (적어도 테스트 한 iOS 6에서는). 당신은 설정할 필요 separatorColor[UIColor clearColor]그 세포가 여전히 1 x 1 픽셀로 구분됩니다, 그래서 당신은 그 차이에 구분을 그릴 수 있습니다 :

- (void)viewDidLoad {
    self.tableView.separatorColor = [UIColor clearColor];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // snip
    CALayer *separator = [CALayer layer];
    separator.backgroundColor = [UIColor redColor].CGColor;
    separator.frame = CGRectMake(0, 43, self.view.frame.size.width, 1);
    [cell.layer addSublayer:separator];
    return cell;
}

cellForRowAtIndexPathtableView 의 다음 코드 대리자를 추가하여 everyCell에 대해 높이 1px 및 너비 200px의 사용자 지정 이미지보기를 만듭니다.

UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 200, self.view.bounds.size.width, 1)];
lineView.backgroundColor = [UIColor blackColor];
[cell.contentView addSubview:lineView];

참고 : 성능에 얼마나 무거운 지 모르겠습니다.


이 작업이 일부 설정으로 "자동으로"수행 될 수 있는지 모르겠습니다. 그러나 제안은 줄 구분 기호를 없음으로 설정하고 셀 테두리에 실제로 원하는 줄 구분 기호를 그립니다.


Swift에서 사용자 지정 셀을 사용하는 경우 : 대안은 해당 셀의 맨 위에 선을 그릴 수있는 함수로 UITableViewCell을 확장하는 것입니다.

import UIKit

extension UITableViewCell {
    func addSeparatorLineToTop(){
        let lineFrame = CGRectMake(0, 0, bounds.size.width, 1)
        let line = UIView(frame: lineFrame)
        line.backgroundColor = UIColor.myGray_300()
        addSubview(line)
    }
}

그런 다음이 줄을 사용자 지정 셀 (예 : awakeFromNib)에 추가 할 수 있습니다.

override func awakeFromNib() {
    super.awakeFromNib()
    addSeparatorLineToTop()
}

이 솔루션은 스토리 보드를 엉망으로 만들지 않고 추가 코드를 한 줄로 제한하기 때문에 좋습니다.


On a retina display, even drawing a 0.5 unit line will result in a two-pixel line, due to anti-aliasing. To render it as a single pixel on both displays, shift it up one quarter of a unit:

UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, self.contentView.frame.size.height - (1.0 - 0.25), self.contentView.frame.size.wi
lineView.backgroundColor = [UIColor colorWithRed:(230.0/255.0f) green:(233/255.0f) blue:(237.0/255.0f) alpha:1.0f];
[self.contentView addSubview:lineView];

Tested on iOS 7 (GM):

@implementation MyTableViewController

- (void)viewDidLayoutSubviews {
    for (UIView *view in self.view.subviews) {
        if ([view isKindOfClass:NSClassFromString(@"_UITableViewCellSeparatorView")])
            view.backgroundColor = [UIColor redColor];
    }
}

@end

NOTE: it appears the UITableView moves separators to the cells in some configurations, which would make this code not work unless you descend into all UITableViewCells as well.


The cell in gist below is a UITableViewCell's subclass where each cell could have its own separator w/ many styles (currently only .None and .Default are supported). It is written in Swift and assumes Autolayout usage.

https://gist.github.com/evgeniyd/fa36b6f586a5850bca3f

How to use the class:

  1. set UITableView object's separator style to UITableViewCellSeparatorStyle.None

    tableView.separatorStyle = .None
    
  2. Create a subclass of MPSTableViewCell

  3. Somewhere inside awakeFromNib() set cell's separator style

Note: the code below assumes cell is loaded from xib/storyboard

    class FASWorkoutCell: FASTableViewCell {

    required init(coder aDecoder: NSCoder) {
         super.init(coder: aDecoder)
     }

     override func awakeFromNib() {
         super.awakeFromNib()

         separatorType = .Default
     }

     // ...

     }

If you use a customized UITableViewCell, You can simply add UIView on the bottom of the UItableViewCell.xib and put the background colour as the colour you want.

For example, on xib I add a UIView on the bottom and set the height as 1. Using autolayout, I set left constraint to 12, bottom constraint to 0, right constraint to 0 and height to 1.


Swift version:

private let kSeparatorTag = 123
private let kSeparatorHeight: CGFloat = 1.5

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath)
{
    if cell.viewWithTag(kSeparatorTag) == nil //add separator only once
    {
        let separatorView = UIView(frame: CGRectMake(0, cell.frame.height - kSeparatorHeight, cell.frame.width, kSeparatorHeight))
        separatorView.tag = kSeparatorId
        separatorView.backgroundColor = UIColor.redColor()
        separatorView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]

        cell.addSubview(separatorView)
    }
}

참고URL : https://stackoverflow.com/questions/1374990/how-to-customize-tableview-separator-in-iphone

반응형