1
votes

I have a UISegmentedControl defined programmatically.

I am trying to add a layout constraint so that when my iPad rotates, the segmented control sizes correctly within the rotated view rather than spill off screen.

I apply the following constraint:

        streamSegmentedControl.translatesAutoresizingMaskIntoConstraints = false

    let segmentedControlWidth = NSLayoutConstraint(item: streamSegmentedControl,
        attribute: .Width,
        relatedBy: .Equal,
        toItem: self.containerView,
        attribute: .Width,
        multiplier: 1.0,
        constant: -10.0)

    containerView.addConstraint(segmentedControlWidth)

My UIsegmentControl is defined as follows:

      streamSegmentedControl = UISegmentedControl(items: ["Today's Events", "Past Events"])
    streamSegmentedControl.frame = CGRectMake(-10,containerView.frame.size.height*0.3,containerView.frame.width+20,40)
    streamSegmentedControl.selectedSegmentIndex = 0
    streamScope = "today"
    streamSegmentedControl.setTitleTextAttributes(segmentedControlFont as [NSObject : AnyObject], forState: .Normal)
    streamSegmentedControl.backgroundColor = UIColor.colorFromClass("background")
    streamSegmentedControl.tintColor = UIColor.colorFromClass("default")


    streamSegmentedControl.addTarget(self, action: "changeStreamScope:", forControlEvents: UIControlEvents.ValueChanged)
    containerView.addSubview(streamTableView)
    containerView.addSubview(streamSegmentedControl)

I don't get an error, but at runtime, my segmented control disappears. Not sure what I am missing here as I've only done auto layout within storyboards in the past.

I only want to be able to adjust the width of the segmented control, so I assume I only need a single layout constraint.

Can anyone give me some direction? Thanks.

1

1 Answers

1
votes

You need to add three constraints at least. Leading, top and trailing. I am weak in swift but your constraints should look like.

let segmentedControlTop = NSLayoutConstraint(item: streamSegmentedControl,
        attribute: .Top,
        relatedBy: .Equal,
        toItem: self.containerView,
        attribute: .Top,
        multiplier: 1.0,
        constant: 0.0)

let segmentedControlLeading = NSLayoutConstraint(item: streamSegmentedControl,
        attribute: .Leading,
        relatedBy: .Equal,
        toItem: self.containerView,
        attribute: .Leading,
        multiplier: 1.0,
        constant: 0.0)

let segmentedControlTrailing = NSLayoutConstraint(item: streamSegmentedControl,
        attribute: .Trailing,
        relatedBy: .Equal,
        toItem: self.containerView,
        attribute: .Trailing,
        multiplier: 1.0,
        constant: 0.0)

containerView.addConstraint(segmentedControlTop)
containerView.addConstraint(segmentedControlLeading)
containerView.addConstraint(segmentedControlTrailing)

If you want to keep a 5 point offset from superview, try playing with constant values of leading and trailing using 5 points.