2016-12-28 71 views
-3

我有阵[["PT"], ["GE", "DE", "PL", "BY"], ["CZ", "US"]],我想在UISegmentedControl我编程方式创建使用它:转换阵列来段中迅速

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

我看到错误:

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

这是真的,但我需要的PT将在第一段标题,GE..BY秒等

+3

段标题是字符串,而不是数组。你期望什么结果?第二部分的标题应该是什么? –

+0

@MartinR我知道,但如何做到这一点'PT'作为字符串将在第一个段,'第二个'GE..BY'等..生成计数段作为主数组中的数组计数 –

回答

2

什么是数组类型?难道[字符串]],那么你就可以做到这一点(游乐场代码):

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

谢谢,但我需要'PT'在第一段,第二段为'GE..BY'等,因此,生成计数段作为主数组中的数组的数量 –

+0

然后@Nirav D回答了你的新问题。 – bubuxu

1

如果你想PT会在第一段,GE..BY在第二和等。因此,尝试这样的。

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) 
    } 
} 
+0

谢谢,我试过@bubuxu的例子,它的工作很好 –

+0

@VadimNikolaev欢迎队友:) –

0

另一种方法是你的阵列映射到标题,就像这样:

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

其中,为let array = [["PT"], ["GE", "DE", "PL", "BY"], [], ["CZ", "US"]]会产生["PT", "GE..BY", "CZ..US"]

,然后将其在UISegmentedControl

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