添加右对齐约束到编程添加的子视图

时间:2017-07-30 15:33:21

标签: ios iphone swift uitableview swift3

我正在尝试将一个右对齐的分段控件添加到`UITableViewCell中:

function find(x){
  var length = 0;
  while(x > 0){
    length++;
    x = x - (10**(length-1)) * length * 9;
  }
  return {length: length, pos: (x % length) + length -1};
}

console.log(find(15));

然后

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "mycell")
    // ...
    addSegmentedControlToCell(cell)
    // ...

这在我的默认设备iPhone 6上运行良好。但是当我在较小宽度的设备上运行此应用程序时,如iPhone 5,以编程方式添加了Segment Control,它接收50%的单元格宽度(cell.frame.size.width / 2)在宽度的50%处看起来要大得多,并且在单元视口下方向右延伸。

这是因为我看到自动布局和约束因为iPhone 5单元格视图被调整大小。所以我试图在我的新段控件中添加一个约束,该控件因app crush而失败。注意,我不是很好地以编程方式添加约束。

func addSegmentedControlToCell(_ cell:UITableViewCell){
    let items = ["One","Two"]
    let unitControl = UISegmentedControl(items: items)
    unitControl.selectedSegmentIndex = 0
    let maxWd = cell.frame.size.width
    let maxHt = cell.frame.size.height
    let padding:CGFloat = 5
    unitControl.frame = CGRect(x:maxWd/2, y:padding, width:maxWd/2, height: maxHt-padding*2)
    unitControl.addTarget(self, action: #selector(SettingsTableViewController.unitControlValueDidChange(_:)), for: .valueChanged)
    cell.addSubview(unitControl)
}

如何正确对齐子视图(段控制)以获得正确的像元大小?

2 个答案:

答案 0 :(得分:0)

您可以设置这样的约束:

yourView.rightAnchor.constraint(equalTo: yourCell.rightAnchor, constant: -10).isActive = true

或者:

yourView.heightAnchor.constraint(equalToConstant: 50).isActive = true

但请确保包含此代码:

yourSegmentedControl.translatesAutoresizingMaskIntoConstraints = false

答案 1 :(得分:0)

您可以通过3种方式完成此操作。 1)你在NSLayoutConstraint中写了0.5常量(这是一个错误)。 你需要写常量是1,乘数应该是0.5。 2)或者你应该在Custom Cell的layoutSubviews()方法中更新UISegmentControl的框架。 3)或者你应该在UIS​​egmentControl添加到Cell之后编写cell.layoutSubviews()。

相关问题