我的應用程序的某個部分我希望用戶能夠選擇表格中的位置,如果他們想要多個位置,並且將這些位置打印到標籤中,以便他們可以看到他們所選擇的整齊和在他們面前。爲了做到這一點,我需要將didSelectRowAt
indexPath放到什麼位置?它們都在同一個ViewController上。Multiple Selection tableView
我不想在選擇表格單元格時轉到另一個視圖控制器。
@IBOutlet weak var labelGifteeLocationsPreview: UILabel!
@IBOutlet weak var tableLocations: UITableView!
let itemsLocations: [String] = ["Pacific Northwest", "West Coast", "The West", "Midwest", "Great Lakes", "The South", "New England"]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemsLocations.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellLocations: UITableViewCell = UITableViewCell()
cellLocations.textLabel?.text = itemsLocations[indexPath.row]
return cellLocations
}
編輯
現在,每當我選擇是從表中越往下一個項目,它帶來的指數超出範圍的錯誤。我不知道爲什麼只有當我選擇離桌子較遠的項目時纔會發生這種情況。下面的代碼:
@IBOutlet weak var tableLocations: UITableView!
let itemsLocations: [String] = ["Pacific Northwest", "West Coast", "The West", "Midwest", "Great Lakes", "The South", "New England"]
@IBOutlet weak var labelGifteeLocationsPreview: UILabel!
var locationsPreviewtext = [String]()
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
locationsPreviewtext.append(itemsLocations[indexPath.row])
labelGifteeLocationsPreview.text = "\(locationsPreviewtext)"
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if locationsPreviewtext.isEmpty {
return
}
else {
let ind = index(ofAccessibilityElement: locationsPreviewtext[indexPath.row]) //this is where I get the index out of range error
if ind == NSNotFound {
locationsPreviewtext.remove(at: indexPath.row)
}
}
labelGifteeLocationsPreview.text = "\(locationsPreviewtext)"
謝謝。我正在使用這個大綱。 – Sarah
答案應該更多地描述解決方案。添加一些評論。 – timiTao