[英]Programmatically get the custom UIViews embedded inside UIStackView
[英]Add UIViews to UIStackView programmatically inside UITableView
我在列表中有三個元素UILabel
, UIImageView
和UIButton
。 我必須在UITableView
相應地顯示它們。 我有一個像這樣的數組:
tableArray = [["label", "img", "button"],["img","button","label"],["img","label","button"],["button", "img", "label"]]
元素的位置與數組內它們的位置(索引)相同。 我的cellForRowAt
看起來像這樣:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "FirstTableViewCell", for: indexPath) as? FirstTableViewCell else {
return UITableViewCell()
}
let tableData = tableArray[indexPath.row]
var count = 0
tableData.forEach { (element) in
switch element {
case "label":
let lbl = self.createLabel()
cell.stackView.insertArrangedSubview(lbl, at: count)
count += 1
break
case "img":
let img = self.createImage()
cell.stackView.insertArrangedSubview(img, at: count)
count += 1
break
case "button":
let btn = self.createButton()
cell.stackView.insertArrangedSubview(btn, at: count)
count += 1
break
default:
break
}
}
return cell
}
問題是,每當這些項添加到單元格中時,每當我滾動TableView
時。
我嘗試過很少的解決方案來解決該問題,但是沒有運氣。
if tableView.cellForRow(at: indexPath) == nil
則將元素添加到stackviews中。
在dequeueReusableCell
之后檢查if cell == nil
。 如果為零,則init
單元格。
let cell = UITableViewCell.init(style: .default, reuseIdentifier: nil) as? FirstTableViewCell
即使沒有dequeueReusableCell
let cell = UITableViewCell.init(style: .default, reuseIdentifier: nil) as? FirstTableViewCell
嘗試過。
但是每次都會發生同樣的事情。
這是FirstTableViewCell
class FirstTableViewCell: UITableViewCell {
@IBOutlet weak var stackView: UIStackView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
任何想法如何檢查元素是否已經添加到StackView
,那么我就不會添加它們。
由於單元已被重用,因此您需要在cellForRowAt
做的第一件事是“重置”您的單元...換句話說,從堆棧視圖中清除現有的子視圖:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "FirstTableViewCell", for: indexPath) as? FirstTableViewCell else {
return UITableViewCell()
}
// remove the views that are currently in the stack
cell.stackView.arrangedSubviews.forEach {
$0.removeFromSuperview()
}
// the rest of your setup
let tableData = tableArray[indexPath.row]
var count = 0
tableData.forEach { (element) in
...
}
現在,根據您提供的代碼,如果單元格始終包含UILabel
, UIImageView
和UIButton
,只是順序不同且具有不同的屬性,則可以在創建單元格時將它們添加一次(或者將它們添加到單元格原型中)。 '),然后根據需要簡單地重新排列它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.