Swift如何在Switch上添加shouldReceiveTouch?

时间:2015-02-05 22:11:32

标签: swift ios8

我正在尝试在UISwitch上添加我的项目shouldReceiveTouch,但我有错误

class ViewController: UIViewController,UIGestureRecognizerDelegate {
var newSwitch: UISwitch!
var deleteButtonIndex:Int!
var deleteSwitchIndex:Int!
let gesture = UILongPressGestureRecognizer()

func CreateSwitchWithIndex(index:Int) {
     let newSwitch = UISwitch()
     newSwitch.tintColor = UIColor.blackColor()
     newSwitch.on = false
     newSwitch.tag = index+1;
     newSwitch.addTarget(self, action: Selector("switchSen:"), forControlEvents: UIControlEvents.ValueChanged)
     self.view.addSubview(newSwitch)
     newSwitch.setOn(false, animated: true)

     let newSwitchConstraintL = NSLayoutConstraint(item: newSwitch, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 50)

    let newSwitchConstraintH = NSLayoutConstraint(item: newSwitch, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 50)

    let coordX = 368
    let coordY = 190 

    newSwitchConstraintX = NSLayoutConstraint(item: newSwitch, attribute: .CenterX, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 0, constant: CGFloat(coordX))

    newSwitchConstraintY = NSLayoutConstraint(item: newSwitch, attribute: .CenterY, relatedBy: .Equal, toItem: view, attribute: .Left, multiplier: 0, constant: CGFloat(coordY))

    view.addConstraints([newSwitchConstraintX,newSwitchConstraintY,newSwitchConstraintH,newSwitchConstraintL])

    var longPress = UILongPressGestureRecognizer(target: self, action: "menu:")
     longPress.minimumPressDuration = 1
     longPress.delegate = self 
     newSwitch .addGestureRecognizer(longPress)
 }

func switchSen(sender:UISwitch!) {
    if (sender.on == true){
        println("on")
    }
    else{
        println("off")
    }
}

func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {

    if(touch.view == newSwitch){
        return false
    }else{
        return true
    }
}

func menu(gesture:UILongPressGestureRecognizer) {

    if(gesture.state == UIGestureRecognizerState.Began){
        self.deleteButtonIndex = gesture.view?.tag
        self.deleteSwichIndex = gesture.view?.tag
        becomeFirstResponder()
        var menu = UIMenuController.sharedMenuController()
        var deleteItem = UIMenuItem(title: "Delete", action: Selector("delete"))
        menu.menuItems = [deleteItem]
        var lastLocation:CGPoint = gesture.locationInView(view)
        menu.setTargetRect(CGRectMake(lastLocation.x, lastLocation.y, 0.0, 0.0), inView: view)
        menu.setMenuVisible(true, animated: true)
    }
}

func delete(){
    println("Delete")
}
}

我刚收到此错误:致命错误:在if(touch.view == newSwitch)上展开Optional值时意外发现nil

如何在Switch上添加shouldReceiveTouch?

1 个答案:

答案 0 :(得分:0)

请尝试使用此行

let newSwitch: UISwitch!

而不是

var newSwitch: UISwitch!