2016-01-07 48 views
1

在我的cellForRowAtIndexPath我添加標籤到我的細胞:爲什麼cell標籤在UITableView中返回相同的值?

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

    cell.fullName.text = self.fullNames[indexPath.row] 

    cell.viewProfile.tag = indexPath.row 
    temp = cell.viewProfile.tag 

    cell.viewProfile.addTarget(self, action: "viewProfile:", forControlEvents: .TouchUpInside) 

    return cell 
} 

其中

var temp = 0 

在上面,類聲明下。

,當我嘗試後:

func viewProfile(sender: UIButton) { 
    print(temp) 
} 

它返回我2,每次在相同的值。爲什麼?我做錯了什麼?

+0

你究竟在做什麼?標籤幾乎肯定不是正確的方法... – Wain

+0

您在桌子視圖中有多少個單元格?如果你有三個臨時值將是2,因爲每次加載單元格時都會覆蓋臨時值。 – Greg

+0

@我只是把按鈕放在UITableViewCell上,當我點擊它時,我想知道這個按鈕的'indexPath.row'通過'addTarget'單擊了單元格。我搜索了很多,並找到了帶有標籤的解決方案。 –

回答

3

如果您嘗試獲取單擊按鈕的索引。然後試試這個

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

    cell.fullName.text = self.fullNames[indexPath.row] 

    cell.viewProfile.tag = indexPath.row 

    cell.viewProfile.addTarget(self, action: "viewProfile:", forControlEvents: .TouchUpInside) 

    return cell 
} 

func viewProfile(sender: UIButton) { 
    print("Index : \(sender.tag)") 
} 

不需要臨時變量。

0

我想你應該重寫方法didSelectRowAtIndexPath來顯示indexPath.row。您始終打印相同的值,因爲在運行cellForRowAtIndexPath的情況下,它始終運行直到顯示在視圖上的最後一個單元格爲止。所以你總是得到相同的臨時變量值。

相關問題