Convert Array of arrays to segments in swift

1k Views Asked by At

I have array [["PT"], ["GE", "DE", "PL", "BY"], ["CZ", "US"]] and I'd like to use it in UISegmentedControl that I created programmatically:

 for i in 0..<array.count {
            mySegmentControl.insertSegment(withTitle: array[i], at: i, animated: false)
        }

I see error:

Cannot convert value of type '[String]' to expected argument type 'String?'

It's true, But I need that PT would be at first segment title, GE..BY at second and etc.

3

There are 3 best solutions below

2
On BEST ANSWER

What's the type of array? Is it [[String]], then you can do this (Playground code):

extension UISegmentedControl {

    func updateTitle(array titles: [[String]]) {

        removeAllSegments()
        for t in titles {
            let title = t.joined(separator: ", ")
            insertSegment(withTitle: title, at: numberOfSegments, animated: true)
        }

    }
}

let control = UISegmentedControl()
control.updateTitle(array: [["PT"], ["GE", "DE", "PL", "BY"], ["CZ", "US"]])
control.titleForSegment(at: 1)
0
On

Another way would be to map your arrays to the titles, like this:

let titles: [String] = array.flatMap {
    guard let first = $0.first else { return nil }
    return first + ($0.count > 1 ? (".." + $0.last!) : "")
}

which, for let array = [["PT"], ["GE", "DE", "PL", "BY"], [], ["CZ", "US"]] would yield ["PT", "GE..BY", "CZ..US"].

And then insert it in your UISegmentedControl:

titles.enumerated().forEach {
    mySegmentControl.insertSegment(withTitle: $0.element, at: $0.offset, animated: false)
}
1
On

If you want PT would be at first segment, GE..BY at second and etc.. So try like this.

for (index,subArray) in array.enumerated() {
     if subArray.count > 1 {
          let title = subArray.first! + ".." + subArray.last!
          mySegmentControl.insertSegment(withTitle: title, at: index, animated: false)
     }
     else if subArray.count > 0 {
          let title = subArray.first!
          mySegmentControl.insertSegment(withTitle: title, at: index, animated: false)
     }
}