2015-08-09 80 views
1

我有一個單元格內的圖像列表,在UITableView。由於我不會(太多)進入的原因,我不能使用didSelectRowAtIndexPath來知道哪一個被選中,因爲我正在使用添加自己的父手勢的第三方模塊,而且我不能設置cancelsTouchesInView = false(這可以在技術上解決我的問題)。Swift:從UITapGestureRecognizer獲取任意信息

在這兩種情況下,是否有一種方法可以向視圖中添加任意信息,以便當我以sender的格式接收它時,我可以對其進行反思。

例如:如果這是HTML & JavaScript,你可以這樣做。

$(myImage).data('foo', 'bar') 
$(anotherImage.data('foo', 'thunk') 

$('img').on('click', function() { 
    console.log($(this).data('foo')) // could be "foo" or "thunk" 
}) 

在斯威夫特

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    var cell = MyCustomTableViewCell() 
    cell.userInteractionEnabled = true 
    let tapped = UITapGestureRecognizer(target: self, action: Selector("myCallback:")) 
    cell.addGestureRecognizer(tapped) 


    // my imaginary world... 
    cell.foo = self.extraData[indexPath.row] 

    return cell 
} 

func myCallback(sender: AnyObject?) { 
    println(sender.foo) 
} 

顯然,上述不工作,但有沒有辦法實現我想要做什麼?

回答

1

儘管我個人不建議使用這麼多,但如果您想在運行時將附加數據附加到對象,則可以使用objc_setAssociatedObject

這裏是如何做到這一點在斯威夫特一個很好的資源:

http://nshipster.com/swift-objc-runtime/


另外,UIView的類有一個名爲tag在那裏你可以指定indexPath.row爲獲得那是單元屬性稍後點擊:

cell.tag = indexPath.row 

順便說一句,你最好不要在細胞上工作。相反,總是在其contentView屬性時要添加手勢或其他子視圖等操作

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    ... 
    cell.contentView.userInteractionEnabled = true 

    // Always remove previously added tap gestures because cells are reused 
    // as you scroll up and down so you'll end up having multiple 
    // recognizers on the same cell otherwise. 
    for recognizer in cell.contentView.gestureRecognizers { 
     cell.contentView.removeGestureRecognizer(recognizer) 
    } 

    cell.contentView.addGestureRecognizer(
     UITapGestureRecognizer(target: self, action: "myCallback:")) 

    cell.contentView.tag = indexPath.row 

    ... 
    return cell 
} 

這是相當簡單的,以獲得在回調函數的單元格:

(假設你只有一節使indexPath.section = 0)

func myCallback(sender: UIGestureRecognizer) { 
    let indexPath = NSIndexPath(forRow: sender.view.tag , inSection: 0)   

    if let cell = tableView.cellForRowAtIndexPath(indexPath) { 
     print("Cell \(cell) has been tapped.") 
    } 
} 
+0

非常好!這就像一個魅力。另外,任何不設置單元格上識別的手勢的理由?它在我的例子中運行良好(意思是,我得到了回調)。 – ded

+0

即使您在單元格上設置了識別器,我認爲它仍然可以工作。但是,根據[Apple文檔](https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UITableViewCell_Class/index),始終處理'contentView'而不是單元格本身是一個好習慣.html#// apple_ref/occ/instp/UITableViewCell/contentView) – ozgur

+0

對不起。不知道我能做到這一點呢。我相當確定<= 200的用戶,他們幾天內不能接受答案 – ded