2017-08-07 22 views
0

迅速新手在這裏。我試圖學習如何以編程方式創建不同的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

現在

,我的想法是,如果我做錯了什麼,細胞不應該出現在所有。我不明白,爲什麼它只顯示在陣列中的一個單元格上?

非常感謝您的幫助。

回答

1

您正在申報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個小時! –

相關問題