2017-07-28 78 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方法,并在单元重用时将代理重置为零。