2017-07-28 74 views
0

我不知道發生了什麼,我設置了button.tag與錶行,當它到達行> 1,它會拋出LLDB。如果button.tag <= 1泰伯維button.tag擲LLDB

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCell(withIdentifier: "cells")! as UITableViewCell 
    let alertBtn = cell.viewWithTag(1) as! UIButton; 
    alertBtn.tag = indexPath.row 
    alertBtn.addTarget(self, action: Selector(("showAlert:")), for: UIControlEvents.touchUpInside) 
    return cell 
} 

enter image description here

+0

它在哪裏拋出error.can你告訴我們,showAlert的implemetation。 – luckyShubhra

+0

錯誤來自於當我設置按鈕標記時,即使我刪除了添加目標,它仍然會拋出相同的錯誤。它與添加目標無關 –

+0

你想讓alertBtn = cell.viewWithTag(1)as做什麼? UIButton的;線。這裏你說的是帶有標籤1的視圖就是你的按鈕,然後你又想改變標籤,所以在重用狀態下你的標籤會有所不同,並且可能的原因是這條線。爲什麼你想從標籤中查看按鈕? –

回答

0

斯威夫特3X ...

正在替換標記,以便第一標籤的物品越來越零,從而將這段代碼...

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
let cell = tableView.dequeueReusableCell(withIdentifier: "cells")! as UITableViewCell 
let alertBtn = cell.viewWithTag(1) as! UIButton 
alertBtn.addTarget(self, action: #selcetor(showAlert(sender:))), for: .touchUpInside) 
return cell 
} 

func showAlert(sender:UIButton) { 
     let point = sender.convert(CGPoint.zero, to: self.tableview) 
     let indexpath = self.tableview.indexPathForRow(at: point) 
} 
+1

感謝它的工作原理!!!,但添加目標現在應該是這樣的。 alertBtn.addTarget(自我,動作:#selector(showAlert(發件人:)),用於:.touchUpInside) –

0

如果你想獲得含有竊聽按鈕,您可以使用類似於此符合要求的功能細胞的indexPath它的工作原理。

func showAlert(sender: AnyObject) { 
     if let cell = sender.superview?.superview as? UITableViewCell{ // do check your viewchierarchy in your case 
       let indexPath = itemTable.indexPath(for: cell) 
      } 
     print(indexPath)// you can use this indexpath to get index of tapped button 
    } 

從的cellForRowAtIndexPath alertBtn.tag = indexPath.row

刪除此行如果您可以使用自定單元爲此,你可以選擇按鈕的indexpath如您之前獲得。

創建CustomCell併爲您的按鈕和標籤等,您可以訪問你的子視圖中的cellForRowAtIndexPath並指定標籤的按鈕創建IBOutlet中。如果您對CustomCell有任何疑問,請告訴我。在這條線上

1

應用程序崩潰,因爲它未能找到與標籤1期,標籤更新與行值每一個細胞。

let alertBtn = cell.viewWithTag(1) as! UIButton 

刪除這條線上,以@IBOutlet爲alertBtn從的UITableViewCell,而不是與標籤耳目一新。

0

嘗試做定製UITableViewCell

申報協議和委託新類的類。連線動作並致電代表

protocol MyCellDelegate: class { 
    func buttonPressed(for cell: MyCell) 
} 

class MyCell:UITableViewCell { 

    weak var delegate: MyCellDelegate? 

    @IBAction func buttonPressed(sender: Any){ 
     self.delegate?.buttonPressed(for: self) 
    } 
} 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
    ....... 
    cell.delegate = self 

    ........ 
} 

記得向VC中添加新的協議實現。您可以添加prepareForReuse方法,並在單元重用時將代理重置爲零。