"Swift"UITableViewCell을 사용하여 TableView에 다양한 내용 표시

12447 단어 Swift

이것은 무엇입니까?


제가 Swift에서 분보 앱을 만들 때, 타임라인을 설치할 때, TableView에 각종 정보를 표시할 때 약간 고전했기 때문에 그 전투의 기록입니다.

완료 이미지


완성된 인상은 바로 이↓↓↓

UITableViewCell 클래스를 사용하여 셀에 다양한 내용 표시


칸에 각양각색의 물건을 표시할 때 순서대로 아래의 일을 하세요.
  • 표시할 내용 가져오기
  • UITableViewCell 클래스 생성
  • UITableViewCell 클래스를 TableView와 연결
  • 속성에 표시할 내용 채우기
  • 표시할 내용 가져오기


    이번에 나는 분보 응용 프로그램이기 때문에 Domain 설치 단계에서 몇 십 글자 정도의 문자열과 날짜를 준비했다.
    Domain에서의 설치에 대해서는 이쪽으로 ↓↓↓
    Swift+Firestore에서 SNS 어플 만들기(Domain 편)
    이 정보는 보고서라는 구조에 포함되어 있다.
    Report.swift
    struct Report {
        var content: String
        var createdAt: Timestamp
    }
    
    보통 Firestore에서 직접 날짜를 얻으면 Timestamp형으로 되돌아옵니다.
    이 사용자 정의 칸은 기본적으로 문자열만 넣을 수 있기 때문에 우선 Timestamp를 String형으로 변환합니다.
    메서드로 형식을 준비하고 한 번에 날짜 형식으로 재정의하여 String에 할당합니다.
    TimelineViewController.swift
    extension TimelineViewController: UITableViewDataSource
    {
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let formatter = DateFormatter()
            formatter.dateFormat = DateFormatter.dateFormat(fromTemplate: "ydMMM", options: 0, locale: Locale(identifier: "ja_JP"))
    
            let date = self.postedReports[indexPath.row].createdAt.dateValue()
            let dateText = formatter.string(from: date as Date)
    

    UITableViewCell 클래스 만들기


    각 셀의 내용을 관리하는 클래스를 만듭니다.
    이 클래스를 이용하여 표시된 내용과 칸의 스타일을 설정할 수 있습니다.
    자세한 내용은 을 참조하십시오애플 공식 문서.
    ReportCell.swift
    class ReportCell: UITableViewCell
    {
        override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
            super.init(style: .subtitle, reuseIdentifier: "ReportCell")
        }
    
        required init(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
    
    기본적으로 문서의 기재에 따라 덮어쓰기init() 방법만 하면 된다
    주의해야 할 것은 세르의 스타일에 관한 것이다.
    super.init(style: style, reuseIdentifier: reuseIdentifier)
    
    애플은 지정init() 방법의 첫 번째 인자를 통해 이 스타일을 변경할 수 있는 몇 개의 셀 스타일을 제공했다.
    스타일의 종류 참조이 문서는 다음과 같이 각각 지정할 수 있는 4가지가 있습니다.
    super.init(style: .default, reuseIdentifier: reuseIdentifier)
    super.init(style: .value1, reuseIdentifier: reuseIdentifier)
    super.init(style: .value2, reuseIdentifier: reuseIdentifier)
    super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
    

    TableView에 UITableViewCell 클래스 연결


    생성된 UITableViewCell 클래스가 tableView와 연결됩니다.
    관련사용UITableView류의register()방법.
    class TimelineViewController: UIViewController
    {
        override func viewDidLoad() {    
            timelineView.register(ReportCell.self, forCellReuseIdentifier: "ReportCell")
        }
    
    register() 메서드의 첫 번째 매개변수는 생성한 UITableViewCell 클래스를 전달합니다.
    두 번째 매개 변수는 반복적으로 사용할 수 있도록 문자열 형식의 사용자 정의 셀 클래스의 이름을 제공합니다.
    이번에는 복잡해지기 때문에 학급 이름과 같다.
    자세한 내용은 공식 문서 을 참조하십시오.
    이것을 잊어버리면 아무리 많은 칸을 사용자 정의해도 바뀌지 않습니다.

    속성에 표시할 내용 채우기


    표시된 칸의 설정도 끝났고, 표시하고 싶은 것도 나왔고, 마침내 칸을 삽입할 수 있게 되었다.
    UITableViewCell 클래스는 다음 세 가지 속성을 제공합니다. 이 속성을 대입하여 칸의 스타일에 따라 표시할 수 있습니다.
    var textLabel: UILabel? //メインの内容を表示できる
    var detailTextLabel: UILabel? //サブコンテンツの表示に使える
    var imageView: UIImageView? //サムネの表示とかはこれが使える
    
    다른 것contentViewbackgroundView 등도 있는데, 어쨌든 위의 3개만 사용하면 그렇게 된다(?)
    extension TimelineViewController: UITableViewDataSource
    {
    
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let reportCell = tableView.dequeueReusableCell(withIdentifier: "ReportCell", for: indexPath)
            let date = self.postedReports[indexPath.row].createdAt.dateValue()
    
            reportCell.textLabel?.text = self.postedReports[indexPath.row].content
            reportCell.detailTextLabel?.text = formatter.string(from: date as Date)
            return reportCell
        }
    

    좋은 웹페이지 즐겨찾기