Quantcast
Channel: FlexMonkey
Viewing all articles
Browse latest Browse all 257

Functional vs Imperative: Creating a Multiline UISegmentedControl in Swift

$
0
0


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 asUIView).subviews.map({($0 as? UILabel)?.numberOfLines = 2})})

...and the second ins the imperative way, using two nested for-in loops:


       for segment insubviews
        {
            for subview in segment.subviews
            {
                iflet 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
        {
            overridefunc didMoveToSuperview()
            {
                for segment insubviews
                {
                    for subview in segment.subviews
                    {
                        iflet segmentLabel = subview as? UILabel
                        {
                            segmentLabel.numberOfLines = 2
                        }
                    }
                }
            }
        }

...and can be implemented as you would a regular UISegmentedControl


Viewing all articles
Browse latest Browse all 257

Trending Articles