Vad
Vad

Reputation: 3740

Adding Right Aligning Constraints to the Programmatically Added Subview

I am trying to add a right aligned Segmented Control to the `UITableViewCell like this:

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

and then

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

This works well on my default device iPhone 6. But when I run this app on a smaller width device, like iPhone 5, the programmatically added Segment Control, which receives 50% of cell width (cell.frame.size.width/2) seems much bigger that 50% of width and stretches to the right under the cell view port.

This is because of auto-layout and constraints as I see because iPhone 5 cell view gets resized. So I am trying to add a constraint to my new Segment Control, which fails with app crush. Note, I am not very good with programmatically adding constraints yet.

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

How to right align subview correctly (Segment Control) for correct cell size?

Upvotes: 0

Views: 989

Answers (2)

krunal
krunal

Reputation: 482

You can do this in 3 ways. 1) You have written 0.5 constant in NSLayoutConstraint(this is a mistake). You need to write constant is 1 and multiplier should be 0.5. 2) Or you should update frame of UISegmentControl in layoutSubviews() method of Custom Cell. 3) Or you should write cell.layoutSubviews() after UISegmentControl adding to Cell.

Upvotes: 0

Phyber
Phyber

Reputation: 1368

You can set constraints like this:

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

Or:

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

But make sure that you include this code:

yourSegmentedControl.translatesAutoresizingMaskIntoConstraints = false

Upvotes: 1

Related Questions