【问题标题】:How to add constraints in Basic Style TableView cell如何在基本样式表视图单元格中添加约束
【发布时间】:2017-08-23 23:08:16
【问题描述】:

我尝试为添加到 UITableView 中基本样式单元格的标签添加约束,但它们未激活。

我使用 Basic Style 而不是 Custom,因为我需要一些行从 Title 开始,另一行从 cell.ImageView!.image

如果我使用自定义单元格,当没有 ImageView 时,标题无论如何都位于远离行左侧的位置。

截图:

【问题讨论】:

  • 请,您应该向我们展示您尝试了什么以及它是如何失败的。我建议你看this 视频,也可以看this。您还可以搜索更多“如何以编程方式创建 tableViewcell
  • 我失败了,因为我找不到任何现有邻居对象条件的约束,因为基本样式单元约束没有激活,我不知道为什么。

标签: swift tableview constraints cell


【解决方案1】:

使用完全自定义的单元格。甚至不要打扰预定义的。自己构建它,您不必担心任何事情,您可以根据需要使用约束(只需确保这些与单元格的内容视图相关,而不是任何其他视图 - UITableViewCell 有很多)。

【讨论】:

  • 感谢您的回答,但如果没有 ImageView,我不知道哪个约束会使标题移到行的左侧。我试图用前导空格将标题粘贴到图像视图,但没有处理。
【解决方案2】:

我在 Apple 文档中找到了答案: https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/ProgrammaticallyCreatingConstraints.html

这段代码正在运行:

import UIKit

class ViewController: UITableViewController {


override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 4
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "ChecklistItem", for: indexPath)

    let label = cell.viewWithTag(1000) as! UILabel
    let image = cell.viewWithTag(1001) as! UIImageView
    let margins = cell.contentView.layoutMarginsGuide

    if indexPath.row == 0 {
        label.text = "First row"
    } else if indexPath.row == 1 {
        label.text = "Second row"
        image.image = UIImage(named: "test")
    } else if indexPath.row == 2 {
        label.text = "Third row"
        label.leadingAnchor.constraint(equalTo: margins.leadingAnchor).isActive = true

    } else if indexPath.row == 3 {
        label.text = "Fourth row"
    }
    return cell
    }
}

Screenshot

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-17
    • 2023-04-11
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多