As I add more features to Nodality, including texture and 3D support, my two UISegmentedControls are running out of space and truncating their labels. Sadly, out of the box, the UISegmentedControl doesn't offer text wrapping, so I've had to create my own component, MultilineSegmentedControl.
My component simply loops over the UISegmentedControl's immediate subviews and then loops over the subviews of each subview. If those subviews are UILabels, it's simply a matter of setting their numberOfLines property to either 0 (for unlimited lines) or, in my case, 2.
However, there are two ways to do this looping.
The first is the functional way, using two nested map() functions:
subviews.map({($0 as UIView).subviews.map({($0 as? UILabel)?.numberOfLines = 2})})
...and the second ins the imperative way, using two nested for-in loops:
for segment in subviews
{
for subview in segment.subviews
{
if let segmentLabel = subview as? UILabel
{
segmentLabel.numberOfLines = 2
}
}
}
My preference is for the latter: I find it far more readable, but your mileage may vary.
The final class, looks like this:
class MultilineSegmentedControl: UISegmentedControl
{
override func didMoveToSuperview()
{
for segment in subviews
{
for subview in segment.subviews
{
if let segmentLabel = subview as? UILabel
{
segmentLabel.numberOfLines = 2
}
}
}
}
}
...and can be implemented as you would a regular UISegmentedControl.
Add a comment