UITableViewCell没有显示Label

时间:2016-08-08 09:16:59

标签: ios uitableview swift2

有人知道这里有什么不对吗?我正在尝试添加一个tableView在我的ParentView的子视图中,UITableView在那里(我可以滚动它但单元格没有显示标签文本)...我的代码:

class ViewController: UIViewController, UITableViewDelegate , UITableViewDataSource {

let containeView = UIView()
var tableView = UITableView()

let mArray = ["HELLO","FROM","THE","OTHER","SIDE"]

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.


    containeView.frame = CGRectMake(20, 20, self.view.frame.size.width - 40, self.view.frame.size.height - 40)
    tableView = UITableView(frame: containeView.bounds, style: .Plain)
    containeView.backgroundColor = UIColor.purpleColor()
    containeView.center = self.view.center
    containeView.addSubview(tableView)
    tableView.delegate = self
    tableView.dataSource = self
    tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
    tableView.reloadData()


    view.addSubview(containeView)

    tableView.reloadData()
 }


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

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return 5
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as? UITableViewCell

        cell = UITableViewCell(style: .Default, reuseIdentifier: "Cell")
        cell?.backgroundColor = UIColor.greenColor()
        cell?.textLabel?.text = mArray[indexPath.row]
        cell?.backgroundColor = UIColor.redColor()
        cell?.textLabel?.textColor = UIColor.blackColor()
        cell?.backgroundColor = UIColor.blueColor()
        print("CELL")


    return cell!
}
}

我试着设置textLabel文本的颜色也尝试设置单元格的背景颜色但是没有对我有用

更新(已解决) 需要为Label添加状态(标签在我选择单元格时出现)

任何人都可以解释我这里发生了什么,我不能选择第1行,当我选择我的行时它会变成灰色,当我选择任何其他行时,之前选中的行变为蓝色,当我滚动时和细胞从屏幕上消失(偏移)它们再次变得不可见,直到我选择任何行,任何线索?

enter image description here

1 个答案:

答案 0 :(得分:2)

尝试将代码修改为

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier("Cell")
    if cell == nil {
        cell = UITableViewCell(style: .Default, reuseIdentifier: "Cell")
        cell?.backgroundColor = UIColor.greenColor()
    }

    cell?.textLabel?.text = mArray[indexPath.row]
    cell?.textLabel?.textColor = UIColor.blackColor()
    print("CELL")

    return cell!
}