簡體   English   中英

UIButton 不適用於自定義 UITableViewCell (Swift)

[英]UIButton doesn't work on a custom UITableViewCell (Swift)

我真的很抱歉我的英語,如果我做錯了什么,這是我在這里的第一個問題。

我有一個自定義 UITableViewCell 作為 *.xib 文件中的視圖。 里面有一個 UIImage 和那個 UIImage 上的一個按鈕。 我將此按鈕與一個插座連接到我的 CustomTableViewCell.swift 類。

@IBOutlet weak var authorImage: UIImageView!
@IBOutlet weak var authorButton: UIButton!

在 MyTableViewController.swift 我注冊了一個筆尖

tableView.registerNib(UINib(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "my_cell")

並編寫了一個 cellForRow... 函數,如下所示:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("my_cell", forIndexPath: indexPath) as! CustomTableViewCell
    cell.authorButton.addTarget(self, action: "authorButtonPressed:", forControlEvents: .TouchUpInside)
    return cell
}

而且,最后我有了這個函數(我在 addTarget 中使用它...):

func authorButtonPressed (sender:UIButton!) {
    print("Hi!")//line1
    print(sender)
}

以及第一行的斷點。 但是這個函數永遠不會被調用。

我也剛剛了解到,當我點擊按鈕時,它沒有動畫。

我該如何修復它或找到解決方法?

先感謝您

您正在使用UIView作為您筆尖中的根視圖。 對於自定義UITableViewCell您需要將根視圖設為 UITableViewCell:

在此處輸入圖片說明

因此,您必須創建一個空的 xib,然后在其上拖動一個 UITableViewCell。 然后開始將您的子視圖添加到ContentView

你不應該在這個函數上添加添加目標:

override func tableView(tableView: UITableView, cellForRowAtIndexPath    indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("my_cell", forIndexPath: indexPath) as! CustomTableViewCell
**cell.authorButton.addTarget(self, action: "authorButtonPressed:", forControlEvents: .TouchUpInside)**
return cell
}

您只需將插座動作添加到您的單元格中。 沒事的。 像這樣的代碼:

@IBAction func testPressed(sender: AnyObject) {
    print("test")
}

按照 joern 解決方案,然后通過單擊它來選擇Table View Cell ,並確保應啟用屬性檢查器窗格的User Interaction Enabled屬性的復選標記。

你用過這個神奇的按鈕嗎? 在此處輸入圖片說明

多虧了它,你可以看到你的圖層樹,它可能包含一些奇怪的東西......就像這樣。 在此處輸入圖片說明

對其他人的看法在那里做得一團糟。 只是調查一下,伙計! 😎

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM