2017-05-18 3 views
1

클래스에서 간단한 tableview를 생성하려고합니다. 셀을 "A"로 만들면 모든 셀에 A를 인쇄 할 수 있지만 현재 코드 출력에서는 빈 테이블이 표시됩니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까? 죄송합니다. 자기 학습 초보자입니다.테이블 뷰 셀에 클래스의 텍스트가 표시되지 않습니다.

import UIKit 

class LinesViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { 

@IBOutlet weak var linesTableView: UITableView! 
let cellID = "cell" 
let lines = ["brown","red","blue"] 

class Train { 
    var color: String = "" 
    var line: String = "" 

    init (color:String?, line:String?){ 
    } 
} 

let brownLine = Train(color: "brown", line: "Brown Line") 
let redLine = Train(color: "red", line: "Red Line") 
let blueLine = Train(color: "blue", line: "Blue Line") 
var trains: [Train] = [] 

override func viewDidLoad() { 
    super.viewDidLoad() 

    // Do any additional setup after loading the view. 
    linesTableView.delegate = self 
    linesTableView.dataSource = self 
    trains = [brownLine,redLine,blueLine] 
    //print (trains[1].line) 

} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 

func numberOfSections(in tableView: UITableView) -> Int { 
    return 1 
} 

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return lines.count 
} 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

    let cell = linesTableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) 

    let train = trains[indexPath.row] 
    cell.textLabel?.text = train.line 

    return cell 
} 
+0

'Train'이니셜 라이저에 값을 지정하는 것을 잊어 버렸으므로 여전히 빈 문자열입니다. –

+0

첫 번째 비주얼을 테스트하기 위해 고정 된 텍스트를 넣으려고 했습니까? 이것을 변경하십시오 : cell.textLabel? .text = train.line for this : cell.textLabel? .text = "Hello"또한 클래스를 올바르게 초기화하지 않았습니다. –

답변

1

클래스 데이터 멤버에 전달 값을 할당하지 않았습니다. 왜 항상 비 었는지.

class Train { 
    var color: String = "" 
    var line: String = "" 

    init (color:String?, line:String?){ 
     self.color = color 
     self.line = line 
    } 
} 
+0

아, 고맙습니다. 코멘트는 정확하지만 syed의 예제는 정확하게 클래스 값을 올바르게 초기화하는 방법을 보여주었습니다. – Lew

관련 문제