2015-02-05 81 views
0

我想在我的UISwitch項目shouldReceiveTouch添加,但我有一個錯誤Swift如何在Switch上添加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") 
} 
} 

我剛剛得到這個錯誤:致命錯誤:意外發現零,而如果上展開的可選值(touch.view == newSwitch)

如何在Switch上添加shouldReceiveTouch?

回答

0

請儘量使用此行

let newSwitch: UISwitch! 

,而不是

var newSwitch: UISwitch! 
相關問題