【问题标题】:Adding Label programmatically in tableView(_:cellForRowAt:) in custom cell在自定义单元格的 tableView(_:cellForRowAt:) 中以编程方式添加标签
【发布时间】:2019-03-11 04:41:26
【问题描述】:

我想在自定义单元格中的 tableView(:cellForRowAt:) 处为自定义单元格添加标签。该单元格最初在自定义单元格的堆栈视图中包含 4 个标签。 之后,我通过 tableView(:cellForRowAt:) 处的代码将 2 个标签添加到同一个堆栈视图。通常,第一次运行是可以的。Stage of customcell at first run

如果我进入其他 viewController 并返回到这个 tableviewController,代码又添加了 2 个标签。每当我切换到其他 viewcontoller 时,这种情况就会不断重复。Label adding up in cell

我可以知道根据 UIViewController 的某些属性实现 customcell 并为 customcell 添加标签的正确方法吗?这个 UIViewController 有一个 String 数组来决定应该向 customcell 添加多少标签。

如果我需要编辑问题,请随时指出。

【问题讨论】:

  • 我猜你有一个问题是因为重用。据我猜测,您在tableView(:cellForRowAt:) 中调用addSubview()
  • “我想在自定义单元格中的 tableView(:cellForRowAt:) 处为自定义单元格添加标签。” - 这是一个矛盾。自定义单元格应该已经有它需要的标签。在cellForRowAt 中您唯一应该做的就是创建单元格并为其提供数据。如果你在cellForRowAt 中调用addSubview,那么你做错了。
  • 这是我如何将标签添加到自定义单元格中 tableView(:cellForRowAt:) 单元格的示例。我知道这是违规行为。我将在测试后星期一回来。我目前没有要测试的mac。 let textLabel = UILabel() textLabel.backgroundColor = UIColor.yellow textLabel.widthAnchor.constraint(equalToConstant: self.view.frame.width).isActive = true textLabel.heightAnchor.constraint(equalToConstant: 20.0).isActive = true textLabel.text = "Hi World" textLabel.textAlignment = .center
  • 是的,我使用 addSubView 将标签添加到 stackview。 self.view.addSubview(stackView) //Constraints stackView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true stackView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
  • @Skron31 请edit您的问题提供所有相关详细信息和代码。

标签: ios swift uitableview uilabel


【解决方案1】:

我认为一种方法是在 prepareForReuse 方法中测试视图是否已经在 stackView 中。如果不是,请插入视图。

override func prepareForReuse() {
    super.prepareForReuse()
    if(stackView.subviews.filter{$0.tag == MYVIEWTAG}.first == nil){
       //ADD VIEWS
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多