2016-12-28 73 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) 
}