Skip to main content
 首页 » 操作系统

ios之仅当在 Swift 中更改为 ON 状态时如何从开关调用选择器

2024年01月01日45webabcd

我需要在改变开关时调用一个带有选择器的函数,但只有当我将开关设置为打开状态时:

 cell.switchMy.addTarget(self, action: "openView", forControlEvents: UIControlEvents.ValueChanged) 
 
  func openView(){ 
    var cell:CustomCell = self.tableView.dequeueReusableCellWithIdentifier("cell5") as CustomCell 
    if(cell.switchMy.on == true){ 
        println("ON") 
        self.performSegueWithIdentifier("segueUnl", sender: self) 
    } 
} 

如果我使用这段代码,总是调用该函数,但我正在控制开关状态是否为 ON...这怎么能正确?

请您参考如下方法:

这是(几乎)正确的方法。您不能只在开关状态为 on 时才调用方法。 但是您不需要从 openView 方法中检索单元格。发送者将由调用者传递:

cell.switchMy.addTarget(self, action: "openView:", forControlEvents: UIControlEvents.ValueChanged) 
 
func openView(sender: UISwitch){ 
    if(sender.on) { 
        println("ON") 
        self.performSegueWithIdentifier("segueUnl", sender: self) 
    } 
} 

注意:addTarget 中使用的选择器需要从 openView 更改为 openView: