2016-09-23 100 views
1

我試圖以編程方式實現一個表視圖單元格中的堆棧視圖與標籤和按鈕添加到它,像這樣:堆棧視圖在表視圖細胞

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) 
    let dict = self.char[indexPath.row] 
    let stackView = UIStackView() 
    stackView.translatesAutoresizingMaskIntoConstraints = false 
    stackView.axis = .horizontal 
    stackView.spacing = 20 
    stackView.distribution = .fillProportionally 
    stackView.alignment = .leading 
    cell.addSubview(stackView) 
    NSLayoutConstraint.activate([ 
     stackView.leadingAnchor.constraint(equalTo: cell.leadingAnchor), 
     stackView.trailingAnchor.constraint(equalTo: cell.trailingAnchor) 
     ]) 
    let bornLabel = UILabel() 
    bornLabel.textColor = UIColor.blue 
    let bornLabelValue = UILabel() 
    bornLabelValue.textColor = UIColor.blue 
    stackView.addArrangedSubview(bornLabel) 
    stackView.addArrangedSubview(bornLabelValue) 
    for (key, value) in dict { 
     bornLabel.text = key 
     bornLabelValue.text = value 
     if key == "Height" { 
      let button = UIButton(type: .roundedRect) 
      button.setTitle("English", for: .normal) 
      button.setTitleColor(.blue, for: .normal) 
     stackView.addArrangedSubview(button) 
     } 
    } 
    return cell 
} 

的問題是,每次tableView.reloadData()被稱爲,另一個單元格被添加到現有的單元格的頂部,每個標籤具有不同的值,具體取決於提供給tableView的數據。或者它可能不會每次生成另一個單元,但只需添加另一個堆棧視圖。我不確定。我怎樣才能解決這個問題?

感謝

回答

2

的問題是,你得到一個「可重複使用的電池」,這意味着這將是一個空的單元中的第幾次,然後它會是一個細胞,你已經增加了一個UIStackView

你應該做一個新的原型細胞,無論是通過Storyboard或新XIB文件,在其中加入了UIStackView,然後只配置stackView在cellForRowAt indexPath:實現。

或者你可以從技術上在stackView中設置一個標籤,然後檢查該標籤的單元格......但請不要這樣做。

+1

您的回答讓我找到了正確的地方,謝謝。我通過確實使用原型單元格,添加了一個stackview並在'cellForRowAt indexPath:'中配置stackview來解決它。我曾嘗試過,並且在'cellForRowAt indexPath:'中實例化了我的標籤和按鈕,而不是在我的自定義單元類中,現在它完美地工作。謝謝! – user2747220

1

嘗試添加stackView在cell.contentView

我的目標-C這樣的人還沒有學會迅速呢。

在目標C中,我們檢查條件,如果在實例化之前單元是零或不是。

ex。

if(cell == nil) 
{ 
    # Instantiate cell here 
} 

by this cell will not instantiate for each row of indexPath。