gpt4 book ai didi

ios - 将 View 动态移动到自动布局中的新位置

转载 作者:搜寻专家 更新时间:2023-11-01 05:38:11 38 4
gpt4 key购买 nike

我有一个自定义的 UITableViewCell 布局,如下所示。它具有三个标签。

enter image description here

标签 2 是可选的。它不存在于每个细胞中。所以我想隐藏它并将 Label 1 向下移动一点,以便在发生这种情况时与 Label 3 居中对齐。

enter image description here

这是我为每个标签添加的约束。

标签 1

enter image description here

标签 2

enter image description here

标签 3

enter image description here

请注意,我添加了一个额外的约束,将中心与 Y 对齐,值为 0 到 Label 1 并将其优先级设置为 750。我想如果我删除 Label 2,优先级较低的约束将取而代之并向下移动。

class TableViewController: UITableViewController {

override func viewDidLoad() {
super.viewDidLoad()

}

// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CustomCell

if indexPath.row == 1 {
cell.label2.removeFromSuperview()
cell.updateConstraints()
}

return cell
}
}

但是好像不行。 标签 2 已删除,但 标签 1 的位置仍然相同。

enter image description here

我怎样才能完成我所追求的?


尝试 #1

根据 T 先生的 answer下面,我向 Label 1 添加了一个顶部约束。然后在 cellForRowAtIndexPath 方法中,我更改了它的值。

override func tableView(tableView: UITableView, cellForRowAtIndexPath 

indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CustomCell

if indexPath.row == 1 {
cell.label2.removeFromSuperview()
cell.topConstraint.constant = cell.bounds.height / 2
cell.layoutIfNeeded()
}

return cell
}

但这也不起作用。

最佳答案

尝试为标签 1 的顶部约束设置一个导出。当您删除标签 2 时,更新标签 1 的顶部约束,即 container.height/2 或者删除顶部约束并给出 centerY 约束到标签 1。如果需要,在更新约束后进行布局。

关于ios - 将 View 动态移动到自动布局中的新位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34418666/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com