【问题标题】:How to add subview to stackview in table view cell?如何在表格视图单元格中将子视图添加到stackview?
【发布时间】:2020-01-29 04:59:13
【问题描述】:

我需要在表格视图单元格中将标签作为子视图添加到 UIStackView。

我已将标签创建为

let nameLabel=UILabel()
nameLabel.text=names[indexPath.row]

其中 name 是一个数组,类型为 String

我的代码是

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource
{
            let names=["Amutha","Priya","Amuthapriya","Priyasri","Kavisha"]
            func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
            {
                return names.count
            }
            func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->
                UITableViewCell
            {
                let cell=tableView.dequeueReusableCell(withIdentifier: "cell") as! ViewCell
                for name in names
                {
                    let nameLabel=UILabel()
                    nameLabel.text=name
                    cell.nameStackView!.addSubview(nameLabel)

                }

                return cell
            }
}

为什么当我向 stackview 添加标签时出现空指针异常?

任何帮助将不胜感激。

【问题讨论】:

  • 显示ViewCell代码
  • 使用UIStackView时,始终使用addArrangedSubview()并添加到其排列的子视图数组中,而不是常规的addSubview(),因为它根据配置自行管理其子视图。
  • @LokSN 你是对的。但这不是崩溃的原因
  • 不是这个意思,只是有一点要说明。从答案上的cmets来看,可能是由于单元格的nameStackView 为nil

标签: ios swift xcode null stackview


【解决方案1】:

改变

cell.nameStackView!.addSubview(nameLabel)

cell.nameStackView!.addArrangedSubview(nameLabel)

【讨论】:

  • 什么样的异常?
  • Unexpectedly found nill while unwrapping an optional value 在这条线上
  • 我认为您没有将 nameStackView IBOutlet 与 Storyboard 或 xib 文件连接。请重新检查。
【解决方案2】:

您可以根据需要使用以下代码添加 UIStackView。

let titleLabel = UILabel()
let subtitleLabel = UILabel()

lazy var titleStackView: UIStackView = {

    titleLabel.textAlignment = .center
    titleLabel.text = "Good Morning"
    titleLabel.textColor = UIColor.white
    titleLabel.font = UIFont(name: "ProximaNova-Regular", size: 12.0)

    subtitleLabel.textAlignment = .center
    subtitleLabel.text = "--"
    subtitleLabel.textColor = UIColor.white
    subtitleLabel.heightAnchor.constraint(equalToConstant: 30.0).isActive = true
    subtitleLabel.font = UIFont(name: "DublinSpurs", size: 20.0)

    let stackView = UIStackView(arrangedSubviews: [subtitleLabel])
    stackView.axis = .vertical/.horizontal
    return stackView
}()

也尝试替换

for name in names
{
    let nameLabel=UILabel()
    nameLabel.text=name
    cell.nameStackView!.addSubview(nameLabel)
}

let nameLabel=UILabel()
nameLabel.text = names[indexPath.row]
cell.nameStackView!.addSubview(nameLabel)

【讨论】:

  • 我必须将数组项作为标签动态添加到堆栈视图
  • 您不应该使用addSubview() 添加到堆栈视图
【解决方案3】:

如果您在 storyboard 或 xib 中有 nameStackView,请确保 IBOutlet 已正确连接。如果您以编程方式创建了nameStackView,请确保它已初始化。

并从堆栈视图中删除所有现有标签,否则每个滚动条上都会有重复的标签

class ViewCell: UITableViewCell {
    //Make sure IBOutlet is connected properly
    @IBOutlet weak var nameStackView: UIStackView!
}

视图控制器

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
{
     let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! ViewCell
     for name in names
     {
        cell.nameStackView.arrangedSubviews.forEach { cell.nameStackView.removeArrangedSubview($0) }
        let nameLabel=UILabel()
        nameLabel.text=name
        cell.nameStackView.addSubview(nameLabel)

     }
     return cell
 }

【讨论】:

    【解决方案4】:

    试试下面的代码

    let nameLabel = UILabel()
    
    cell.nameStackView.addArrangedSubview(nameLabel)
    

    【讨论】:

      【解决方案5】:

      尝试在 ViewCell 类中初始化堆栈视图和标签。

      class ViewCell: UITableViewCell {
          let nameLabel: UILabel = {
              let label = UILabel()
              label.font = UIFont.systemFont(ofSize: 14)
              return label
          }()
          let nameStackView: UIStackView = {
              let stackView = UIStackView()
              stackView.axis = .vertical
              return stackView
          }()
          override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
              super .init(style: style, reuseIdentifier: reuseIdentifier)
              self.configureStackView()
          }
      
          required init?(coder aDecoder: NSCoder) {
              fatalError("init(coder:) has not been implemented")
          }
      
          func configureStackView()
          {
              addSubview(nameStackView)
              nameStackView.translatesAutoresizingMaskIntoConstraints = false
              nameStackView.topAnchor.constraint(equalTo: topAnchor).isActive = true
              nameStackView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
              nameStackView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
              nameStackView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
      
              nameStackView.addArrangedSubview(nameLabel)
              nameLabel.translatesAutoresizingMaskIntoConstraints = false
              nameLabel.topAnchor.constraint(equalTo: nameStackView.topAnchor, 
              constant:10).isActive = true
              nameLabel.leadingAnchor.constraint(equalTo: nameStackView.leadingAnchor, 
              constant:10).isActive = true
              nameLabel.trailingAnchor.constraint(equalTo: nameStackView.trailingAnchor, 
              constant:-10).isActive = true
              nameLabel.bottomAnchor.constraint(equalTo: nameStackView.bottomAnchor, 
              constant:-10).isActive = true
          }
      }
      

      此代码是在您没有在情节提要中创建 stackview 的情况下使用的。

      现在在您的 ViewController 类中,在您的 cellForRowAt 方法中添加以下代码。

      func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->
                      UITableViewCell
      {
          let cell=tableView.dequeueReusableCell(withIdentifier: "cell") as! ViewCell
          cell.nameLabel.text = names[indexPath.row]
          return cell
      }
      

      希望,此解决方案适合您。

      【讨论】:

        猜你喜欢
        • 2021-06-04
        • 1970-01-01
        • 2019-04-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多