2017-07-30 36 views
0

我想对齐分段控制权添加到`的UITableViewCell这样的:添加右对齐约束的编程方式添加子视图

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

然后

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) 
} 

这非常适用于我的默认设备的iPhone 6.但是,当我运行这个应用程序在一个较小的宽度的设备,如iPhone 5,编程添加段控制,接收50%的单元格宽度(cell.frame.size.width/2)似乎远大于50宽度的百分比并在单元视图端口下向右延伸。

这是因为我看到自动布局和约束,因为iPhone 5单元格视图被调整大小。所以我正在尝试向我的新Segment Control添加一个约束,该约束与app crush失败。请注意,我不太擅长以编程方式添加约束。

let widthContr = NSLayoutConstraint(item: unitControl, 
             attribute: NSLayoutAttribute.width, 
             relatedBy: NSLayoutRelation.equal, 
             toItem: cell, 
             attribute: NSLayoutAttribute.notAnAttribute, 
             multiplier: 1, 
             constant: 0.5) 
    cell.addConstraints([widthContr]) 

如何正确对齐子视图(段控制)的正确的单元格大小?

回答

0

您可以设定限制这样的:

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

或者:

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

但要确保你有这样的代码:

yourSegmentedControl.translatesAutoresizingMaskIntoConstraints = false 
0

您可以通过三种方式做到这一点。 1)你在NSLayoutConstraint中写入了0.5个常量(这是一个错误)。 你需要写的常数是1,乘数应该是0.5。 2)或者你应该在Custom Cell的layoutSubviews()方法中更新UISegmentControl的帧。 3)或者你应该在UIS​​egmentControl添加到单元格之后编写cell.layoutSubviews()。

相关问题