2017-01-03 40 views
2

我正在用UILabel創建自定義UITableViewCells,但無法獲得標籤顯示在單元格左上角looks like this以外的任何地方。自定義UITtableViewCell不工作的佈局約束

約束似乎還沒有被應用,他們被稱爲(到達斷點)。我嘗試用UIImageView替換UILabel並應用相同的約束,但沒有出現(即表格視圖單元格爲空)。

我錯過了什麼?

信息查看電池:

import UIKit 

class myTableViewCell: UITableViewCell { 

    override init(style: UITableViewCellStyle, reuseIdentifier: String!) { 
     super.init(style: style, reuseIdentifier: reuseIdentifier) 
     setupViews() 
    } 

    required init?(coder decoder: NSCoder) { 
     super.init(coder: decoder) 
    } 

    let label: UILabel = { 
     let label = UILabel() 
     label.translatesAutoresizingMaskIntoConstraints = false 
     label.font = UIFont.systemFont(ofSize: 16, weight: UIFontWeightLight) 
     label.text = "Sample" 
     label.backgroundColor = UIColor.red 
     return label 
    }() 

    func setupViews() { 
     addSubview(label) 
     //add constraints 
     let marginsGuide = self.contentView.layoutMarginsGuide 
     label.leadingAnchor.constraint(equalTo: marginsGuide.leadingAnchor).isActive = true 
     label.trailingAnchor.constraint(equalTo: marginsGuide.trailingAnchor).isActive = true 
     label.topAnchor.constraint(equalTo: marginsGuide.topAnchor).isActive = true 
     label.bottomAnchor.constraint(equalTo: marginsGuide.bottomAnchor).isActive = true 
    } 

} 

視圖控制器:

import UIKit 

class myViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 

    var myTableView: UITableView = UITableView() 

    var myArray = [Int]() 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     //... do stuff incl. loading data into my myArray 
     let screenSize: CGRect = UIScreen.main.bounds 
     self.myTableView.frame = CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height) 
     self.myTableView.delegate = self 
     self.myTableView.dataSource = self 
     self.myTableView.register(IngredientListTableViewCell.self, forCellReuseIdentifier: "cell") 
     self.view.addSubview(myTableView) 
    } 

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = self.myTableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! myTableViewCell 
     return cell 
    } 

} 

回答

0

更改此

addSubview(label) 

這個

contentView.addSubview(label) 
+0

作品。注意到self.contentView.addSubview(標籤)也適用。你能幫我理解發生了什麼嗎? – kipepeo

+0

在表格視圖單元格中,始終使用內容視圖。該視圖在那裏爲單元格的內容。由此得名。您的代碼無法正常工作,因爲您使用了內容視圖的邊距('let marginsGuide = self.contentView.layoutMarginsGuide'),但將子視圖添加到單元格本身。 – dasdom