按钮或开关上的Swift UILongPressGesture

时间:2015-02-03 22:43:37

标签: swift ios8

我试图找出我用UILongPressGesture按下的是按钮或开关函数删除

 func delete() {
    let subviews = self.view.subviews as [UIView]
    for v in subviews {
        if let button = v as? UIButton {
           println("button")
        }
        else if let loadSwitch = v as? UISwitch {
           println("switch")
        }
   }

我有一个打印按钮和开关

当我只是按钮时我没有问题,但现在我已经集成了开关......

PS开关上的长按只有当我按下开关本身下方才能得到它

1 个答案:

答案 0 :(得分:0)

您可以使用isKindOfClass

查看您的UIViews的类型
for v in subviews {
    if(v.isKindOfClass(UIButton)){
        //Do button stuff
    }else if(v.isKindOfClass(UISwitch)){
        //Do switch stuff
    }
}

但是现在仍然存在切换问题。问题是,UILonGestureRecognizer不会被调用,因为其他UISwitch操作之前会激活。但是你可以通过使用UIGestureRecognizerDelegate方法shouldReceiveTouch来阻止它:

class test:UIViewController, UIGestureRecognizerDelegate{

    func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
        //If it's your switch, the normal gesture won't be called.
        if(touch.view == yourSwitch){
            return false
        }else{
            return true
        }
    }

}