2015-08-25 68 views
1

在我的代碼中,我有一個表格視圖來加載使用我的應用程序的用戶的名稱。當用戶選擇一行時,它會顯示一個複選標記。我想要做的是保存一個包含所有選定行的數組(該數組將包含名稱)。我發現了一些信息,但我仍然在學習iOS編程,而我不知道Obj-c。如何存儲選定行的數組?

這是我迄今所做的:

var selectedMembers = [String]? 
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return self.names?.count ?? 0 
    } 

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCellWithIdentifier("UserCell") as! UITableViewCell 

     cell.textLabel!.text = names![indexPath.row] 

     return cell 
    } 


func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) 
{ 
    selectedMembers = Array() 
    if let cell = tableView.cellForRowAtIndexPath(indexPath) { 

     if cell.accessoryType == .Checkmark 
     { 
      cell.accessoryType = .None 

      self.selectedMembers?.remove(indexPath) 

     } 
     else 
    { 
     cell.accessoryType = .Checkmark 
     self.selectedMembers?.append(indexPath) 
     } 
    } 
} 
+0

[Swift - 將數組寫入文本文件]的可能重複(http://stackoverflow.com/questions/24977139/swift-write-an-array-to-a-text-file) –

+0

只需檢查此內容問,是關於如何將斯威夫特數組保存到一個文件http://stackoverflow.com/questions/24977139/swift-write-an-array-to-a-text-file –

+0

是你的問題如何保存爲陣稍後使用或如何獲取選定成員的名稱(行中的字符串) – milo526

回答

2

要得到你需要使用所選行,並獲得該行的進入你的數組名的名稱。

要獲得indexpath的行,你可以使用

indexPath.row 

爲了讓您的成員的名字,你會用

names![indexPath.row-1] 

Ofcourse你這個保存到使用陣列

self.selectedMembers?.append(names![indexPath.row-1]) 

刪除項目,您將需要添加一個額外的步驟

self.selectedMembers?.removeAtIndex(selectedMembers.indexOf(names![indexPath.row-1])) 
+0

使用此解決方案我收到消息:「致命錯誤:數組索引超出範圍。」我刪除了「-1」,並在我的數組中獲得了所選最後一個成員的名稱。 –

+0

您能否指定哪一行返回錯誤? – milo526

+0

這條線:(!名字[indexPath.row-1])\t self.selectedMembers .append。當我選擇該行時,該應用程序崩潰。 –

0

您可以使用didSelectRowAtIndexPath和didDeselectRowAtIndexPath委託方法來跟蹤表中的索引路徑。

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 

    selectedIndexPaths.append(indexPath) 

} 

func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { 

    if let index = find(selectedIndexPaths, indexPath) { 
     selectedIndexPaths.removeAtIndex(index) 
    } 

} 

然後您可以回溯並使用索引路徑獲取選定的對象。

+0

它給我的消息:「無法調用」附加「類型的參數列表(NSIndexPath)」。「在該行selectedMembers.append(indexPath) –

+0

確保您intialize像這樣'變種selectedIndexPaths = [NSIndexPath]()' – jherg

+0

嘿什麼的發現(selectedIndexPaths,indexPath)? m得到錯誤使用解析標識符'find'。 – deltami

相關問題