我有一个定制的UITableViewCell
布局,看起来像这样。它具有三个标签。
标签2 是可选的。它并不存在于每个单元格中。因此,我想将其隐藏起来,并在发生这种情况时将标签1 向下移动一点,以便与标签3 居中对齐。
这是我为每个标签添加的约束。
标签1
标签2
标签3
注意,我添加了一个额外的约束,将y的中心居中Y对齐到标签1 ,并将其优先级设置为750。我确定如果删除标签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 的位置仍然相同。
我该如何完成我的追求?
尝试#1
根据下面T先生的answer,我在标签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时,更新label1的顶部约束即container.height / 2或移除顶部约束并为标签赋予centerY约束1.更新约束后,如果需要,请进行布局。
关于ios - 动态将 View 移动到自动布局中的新位置,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34418666/