2016-02-29 16 views
0

我有一個帶有變量的UITableViewCell中的字符串。 例如:VAR的TodoItem:字符串=字符串( 「名稱:\(名稱)及數量:\(數量)和顏色:\(顏色)」。從插入的字符串取回變量

此被顯示爲在tableview中細胞的字符串 的名稱被添加到名稱的[String]中並且數量被添加到數量的int數組[Int]中,等等。

如果我方便刪除單元格,我應該能夠刪除名稱,數量和但是由於這是一個字符串,我必須能夠單獨訪問這些變量以從相關數組中扣除。

如何獲得對變量的訪問,給定插入的字符串?

謝謝。

+2

從拍攝的東西舉行字符串轉換爲特定類型稱爲解析。我不會這樣做,我會儲存一些變量,從單元格創建的第一個地方。但是如果必須的話,你可以將字符串拆分並將這些部分解析爲適當的變量。 – Carlos

+0

爲了從'String'中檢索值,我們可以使用正則表達式。請參閱文檔:https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSRegularExpression_Class/和一個不錯的教程 –

回答

0

如果你的價值觀都在形成「鍵:值」後面有一個空格或字符串的末尾,則該功能可能會爲你工作:

import Foundation 

func valueFromKeyInString(key:String, string:String) -> String? { 
    if let keyRange = string.rangeOfString(key) { 
    let endIndex = string.rangeOfString(" ", options: [], range: 
     (keyRange.startIndex..<string.endIndex), locale: NSLocale.currentLocale())?.startIndex ?? 
     string.endIndex 
     return string.substringWithRange(keyRange.endIndex..<endIndex) 
    } 
    return nil 
} 

// how it's used: 
let string = "the name:bob and quantity:12 and color:red" 
let name = valueFromKeyInString("name:", string: string)   // => "bob" 
let quantity = valueFromKeyInString("quantity:", string: string) // => "12" 
let color = valueFromKeyInString("color:", string: string)  // => "red" 

然後,您可以使用這些字符串轉換成你需要的值。

正則表達式也可以工作,但如果你能確定字符串的格式,這是一個相當簡單的解析。當然,如果您有權訪問實際值,那麼您應該嘗試獲取這些值,而不是解析字符串。

0

@Carlos是對的 - 你不想從你創建的表示字符串中解析數據。您必須已經namequantitycolor存儲變量的地方,你在cellForRowAtIndexPath

使用。如果數據已經存儲在陣列中,當你刪除單元格是否可以訪問,使用indexPath找到數據的陣列。

下面是一個例子我前面,我的數據在陣列sourceAlbumNames

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int 
{ 
    return sourceAlbumNames.count; 
} 

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell 
{ 

    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell 


    cell.textLabel?.text = sourceAlbumNames[indexPath.row] as String 

    return cell 
} 

我想你已經有這樣的事情對於刪除

func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) { 
    if (editingStyle == UITableViewCellEditingStyle.Delete) { 
     // handle delete (by removing the data from your array and updating the tableview) 

     sourceAlbumNames.removeAtIndex(indexPath!.row) 
     tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) 
    } 
} 
+0

我有他們在數組中。但是indexPath.row返回一個UITableViewCell對象。如何從那裏去?你能給個例子嗎? – user3617409

+0

我已經更新了我的答案以包含示例 – Russell