编程的UITableView是示出一个小区只

问题描述:

迅速新手在这里。我试图学习如何以编程方式创建不同的UI元素。我已经打了以下的墙..编程的UITableView是示出一个小区只

我有2个.swift文件,一方面,我们有......

import UIKit 

struct MyTableView { 

let myCustomTable: UITableView = { 

    let aTable = UITableView() 
     aTable.register(MyCustomCell.self, forCellReuseIdentifier: "myCell") 

    return aTable 
    }() 

} 

// custom cell class, then add subviews (UI controls) to it 

class MyCustomCell: UITableViewCell { 

override init(style: UITableViewCellStyle, reuseIdentifier: String?) { 
    super.init(style: style, reuseIdentifier: reuseIdentifier) 

    addSubview(aLabel) 
    aLabel.frame = CGRect(x:0, 
          y:0, 
          width:self.frame.width, 
          height:self.frame.height) 
} 

required init?(coder aDecoder: NSCoder) { 
    fatalError("init(coder:) has not been implemented") 
    } 

} 

// stuff to add to the cell 

let aLabel: UILabel = { 

    let lbl = UILabel() 
     lbl.text = "My Custom Cell" 
     lbl.backgroundColor = UIColor.yellow // just to highlight it on the screen 

    return lbl 
}() 

在另一方面,我们有以下视图控制器...

import UIKit 

    class ViewControllerA: UIViewController, UITableViewDelegate, UITableViewDataSource { 

     private let instanceOfViewControllerTable = MyTableView() 

     override func loadView() { 

      super.loadView() 

       view.frame = UIScreen.main.bounds 

      instanceOfViewControllerTable.myCustomTable.delegate = self 
      instanceOfViewControllerTable.myCustomTable.dataSource = self 

      instanceOfViewControllerTable.myCustomTable.frame = CGRect(x:0, 
                     y:0, 
                     width:self.view.frame.width, 
                     height:self.view.frame.height) 

      self.view.addSubview(instanceOfViewControllerTable.myCustomTable) 


     } 


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

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

      return tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) 

     } 

    } 

它建立并成功运行,但是,我得到以下结果:

screenshot from table view

现在

,我的想法是,如果我做错了什么,细胞不应该出现在所有。我不明白,为什么它只显示在阵列中的一个单元格上?

非常感谢您的帮助。

您正在申报aLabel全局变量。这样,只有一个实例存在。将其移动到您单元格的类声明中。

class MyCustomCell: UITableViewCell { 
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) { 
     super.init(style: style, reuseIdentifier: reuseIdentifier) 

     addSubview(aLabel) 
     aLabel.frame = CGRect(x:0, 
           y:0, 
           width:self.frame.width, 
           height:self.frame.height) 
    } 

    required init?(coder aDecoder: NSCoder) { 
     fatalError("init(coder:) has not been implemented") 
    } 

    let aLabel: UILabel = { 
     let lbl = UILabel() 
     lbl.text = "My Custom Cell" 
     lbl.backgroundColor = UIColor.yellow // just to highlight it on the screen 

     return lbl 
    }() 
} 
+0

我知道它会像支架或点一样微不足道。感谢你的帮助。一直在尝试它2个小时! –