2016-09-29 70 views
0

我有一个UITableViewUITableViewCell s其accessoryViewUIButton s。当用户按下这个UIButton时,会触发一个动作。它工作的很好,但有一个不方便:accessoryView没有卡在单元格的右边缘,所以当用户按下单元格的最右侧时,按钮不会被触发,甚至更糟糕:单元格被选中,触发不想要的行为。如何在UITableViewCell的某个位置禁用用户交互?

这是我如何定义我的细胞:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

    let cell = tableView.dequeueReusableCell(withIdentifier: "CellIdentifier") 

    let accessoryButton = MyCustomAccessoryView(frame: CGRect(x: 0.0, y: 0.0, width: 45.0, height: 45.0)) 
    accessoryButton.addTarget(self, action: #selector(MyController.accessoryButtonTapped(_:)), for: .touchUpInside) 
    cell?.accessoryView = accessoryButton 

    return cell 
} 

MyCustomAccessoryView.swift:

class MyCustomAccessoryView: UIButton { 

    override init(frame: CGRect) { 
     super.init(frame: frame) 

     self.backgroundColor = UIColor.red 
    } 

    required init?(coder aDecoder: NSCoder) { 
     super.init(coder: aDecoder) 
    } 
} 

下面是结果:

enter image description here

所以我的问题是:有一种方法可以禁用012最右侧的用户交互?

回答

0

您应该添加按钮作为您的单元格内容视图的子视图。所以你可以为你的按钮设置所需的框架,并且你的cell不会显示额外的空间。

因此,添加按钮的contentviewsubview

第二件事,如果你想设置按钮作为配件视图,然后在右侧添加另一个blank labelblank view,所以它不会得到click

上述解决方案将是你而不是管理复杂的东西,比如更好的 - 对特定区域等禁用userinteraction

+0

谢谢,但我试图添加按钮,我的单元格的内容的子视图,并有按钮和电池(几乎是不可能的触摸按钮,即使'gestureRecognizer之间的巨大冲突:shouldRequireFailureOf:'方法来实现,该细胞是点击按钮时选择)。 我没有得到你的第二个解决方案:如果我在右侧放置一个空白视图,点击这个视图将选择单元格,对不对? – Randy

相关问题