简体   繁体   中英

How to increase UISegmentedControl total width?

To be clear up front, I'm NOT asking how to modify the width of the individual UISegmentedControl segments, or buttons.

My end-goal is to create a UISegmentedControl embedded in a UIScrollView . This UISegmentedControl will have the ability to indefinitely increase the number of its segments.

To accomplish this, I need to increase the total width of the UISegmentControl itself, each time a segment is added. Is there any way I can increase total width without recreating a brand new UISegmentedControl object each time I add a segment?

Thank you, in advance!

@MatthiasBauch's comment helped me track down the whole solution, as detailed below:

NOTE : I'm using Autolayout, so anywhere I use the Storyboard you'll have to substitute it with the programmatic equivalent.

1) First, drag a "Segmented Control" out on the the storyboard.
2) Create an Outlet for the Control you just added.
3) Also, ctrl+click on the Control, and drag to itself. Then click on "width" to add a width constraint.
4) Now, open the Document Outline (Editor > "Reveal Document Outline")
5) Open the "View" that the Segmented Control is in, then open the dropdown for the Segmented Control (mine was named "First, Second" by default). Then open "Constraints".
6) Ctrl+click on the "Width" constraint you just made and drag over to your view controller to create an Outlet for it. This will allow you to adjust the width programmatically.

Using the article mentioned below, you can update the constraint as follows (using animation...bonus!)

Go to the method you want to use to update the width and do the following:

let desiredWidthChange = 30.0

self.widthConstraint.constant = 
    self.mySegmentedControl.constant + desiredWidthChange

self.mySegmentedControl.setNeedsUpdateConstraints()

UIView.animateWithDuration(0.5, animations: { () -> Void in
    self.mySegmentedControl.layoutIfNeeded() // Captures all of the frame changes.
    println("Width updated successfully")
})

Reference:
Are NSLayoutConstraints animatable?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM