如何单击位于UITableView下方的按钮

时间:2016-09-13 04:09:20

标签: ios uitableview

说,我有一个位于UITableView下的按钮,如何点击UITableViewCell中的按钮,但不要触发单元格点击事件:

enter image description here

我把按钮放在tableview后面的原因是我想看到并单击颜色设置为清晰的单元格下的按钮,当我滚动表格时,按钮可以被不包含的单元格所覆盖颜色鲜艳

3 个答案:

答案 0 :(得分:2)

在主视图上获取触摸点。然后使用以下方法检查触摸点是否位于按钮框内。

bool CGRectContainsPoint(CGRect rect, CGPoint point)

答案 1 :(得分:2)

我创建了一个示例项目并使其正常工作:

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

    let tap = UITapGestureRecognizer(target: self, action: #selector(TableViewVC.handleTap))
    tap.numberOfTapsRequired = 1
    self.view.addGestureRecognizer(tap)
}

func handleTap(touch: UITapGestureRecognizer) {
    let touchPoint = touch.locationInView(self.view)
    let isPointInFrame = CGRectContainsPoint(button.frame, touchPoint)

    print(isPointInFrame)

    if isPointInFrame == true {
        print("button pressed")
    }
}

要检查按钮是否真的被按下,我们需要使用长按手势:

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

    let tap = UILongPressGestureRecognizer(target: self, action: #selector(TableViewVC.handleTap))
    tap.minimumPressDuration = 0.01
    self.view.addGestureRecognizer(tap)
}


func handleTap(touch: UILongPressGestureRecognizer) {
    let touchPoint = touch.locationInView(self.view)

    print(" pressed")
    if touch.state == .Began {
        let isPointInFrame = CGRectContainsPoint(button.frame, touchPoint)
        print(isPointInFrame)

        if isPointInFrame == true {
            print("button pressed")
            button.backgroundColor = UIColor.lightGrayColor()
        }
    }else if touch.state  == .Ended {

        button.backgroundColor = UIColor.whiteColor()
    }
}

答案 2 :(得分:2)

您可以将自定义视图编写到顶视图后面的触摸按钮或特殊视图

class MyView: UIView {

    override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
        for subview in self.subviews {
            if subview is UIButton {
                let subviewPoint = self.convertPoint(point, toView: subview)
                if subview.hitTest(subviewPoint, withEvent: event) != nil { // if touch inside button view, return button to handle event
                    return subview
                }
            }
        }
        // if not inside button return nomal action
        return super.hitTest(point, withEvent: event)
    }
}

然后将控制器视图设置为自定义MyView类

enter image description here