【问题标题】:Swift/UISwitch: how to implement a delegate/listenerSwift/UISwitch:如何实现委托/侦听器
【发布时间】:2015-12-11 18:07:36
【问题描述】:

在我的 UITableViewController 中,我有一个自定义单元格,其中包含一个切换器,如下所示:

import Foundation
import UIKit

class SwitchCell: UITableViewCell {
  @IBOutlet weak var label : UILabel!
  @IBOutlet weak var switchEmail : UISwitch!

  func setEditable(canEdit:Bool) {
      if (canEdit) {
        self.switchEmail.enabled = true
        self.label.highlighted = false
      }
      else {
          self.switchEmail.enabled = false
          self.label.highlighted = true
      }
  }

  func configureCellWithSwitch(labelText:String, switchValue:Bool, enabled:Bool) {

    var labelFrame:CGRect = self.label.frame
    labelFrame.size.height = Settings.labelHeight
    self.label.frame = labelFrame

    self.label.text = labelText

    if (switchValue) {
        self.switchEmail.setOn(true, animated: true)
    }
    else {
        self.switchEmail.setOn(false, animated: true)
    }

    self.setEditable(enabled)

  }
}

我想知道如何实现切换器的侦听器/委托,以便从 UITableViewController 获取其值。我能够使用 UITextField 和 UITextView 为单元格编写委托/侦听器来实现方法

func controller(controller: UITableViewCell, textViewDidEndEditing: String, atIndex: Int)

func controller(controller: UITableViewCell, textFieldDidEndEditingWithText: String, atIndex: Int)

但我不知道应该实现什么切换器。

【问题讨论】:

    标签: ios swift uitableview uiswitch


    【解决方案1】:

    UISwitch 没有委托协议。您可以按如下方式收听状态:

    对象:

    // somewhere in your setup:
    [self.mySwitch addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
    
    
    - (void)switchChanged:(UISwitch *)sender {
       // Do something
       BOOL value = sender.on;
    }
    

    斯威夫特:

    mySwitch.addTarget(self, action: "switchChanged:", forControlEvents: UIControlEvents.ValueChanged)
    
    func switchChanged(mySwitch: UISwitch) {
       let value = mySwitch.on
       // Do something
    }
    

    Swift3:

    mySwitch.addTarget(self, action: #selector(switchChanged), for: UIControlEvents.valueChanged)
    
    func switchChanged(mySwitch: UISwitch) {
        let value = mySwitch.isOn
        // Do something
    }
    

    Swift4:

    mySwitch.addTarget(self, action: #selector(switchChanged), for: UIControl.Event.valueChanged)
    
    @objc func switchChanged(mySwitch: UISwitch) {
        let value = mySwitch.isOn
        // Do something
    }
    

    【讨论】:

    • 好的,这就是我刚刚在 init() 的类单元格中编写的内容。我想知道如何从我的表视图控制器中检索开关值...我应该在那里实现哪种方法?
    • @LoryLory 查看我的更新:UISwitch 的值可通过.on 获得
    • 啊好吧,那个方法应该在TableView里面吧?我以为它在自定义类单元格中......这就是为什么我不知道如何从表格视图控制器中获取值
    • 别忘了,在init过程中做addTarget,但是把func switchChanged放在外面
    【解决方案2】:

    在 Swift4.0 中

    mySwitch.addTarget(self, action: #selector(valueChange), for:UIControlEvents.valueChanged)
    
     @objc func valueChange(mySwitch: UISwitch) {
            let value = mySwitch.isOn
            // Do something
            print("switch value changed \(value)")
        }
    

    【讨论】:

      【解决方案3】:

      Swift 3:

      使用情节提要自动布局:

      添加参考:

      @IBOutlet weak var sampleSwitch: UISwitch!
      

      关联方法:

      @IBAction func sampleSwitchValueChanged(_ sender: Any) {
      
          if sampleSwitch.isOn {
              print("ON")  
          }
          else {
              print ("OFF")
          }
      }
      

      程序化方式:

      添加目标:

      sampleSwitch.addTarget(self, action: #selector(ViewController.sampleSwitchValueChanged(sender:)), for: UIControlEvents.valueChanged)
      

      与开关关联的方法:

         func sampleSwitchValueChanged(sender: UISwitch!)
          {
              if sender.isOn {
      
                  print("switch on")
      
              } else {
      
              }
          }
      

      【讨论】:

        【解决方案4】:

        另一种(Swift 3 或 4)方法是使用 didSet 观察者并大幅减少代码,就像这样-

        在类声明中声明如下变量:

        var switchFlag: Bool = false {
                didSet{               //This will fire everytime the value for switchFlag is set
                    print(switchFlag) //do something with the switchFlag variable
                }
            }
        

        然后你可以像这样在UISwitch 上有一个IBAction

        @IBAction func switchChanged(_ sender: Any) {
                if self.mySwitch.isOn{
                    switchFlag = true
                }else{
                    switchFlag = false
                }
            }
        

        【讨论】:

        • 好主意!我不知道为什么之前没有人描述过使用@IBAction 方法的简单解决方案。
        【解决方案5】:

        在 Swift 5 中

        switchDemo.addTarget(self, action: #selector(didTapAdvertise), for:UIControl.Event.valueChanged)
        
        @objc func didTapAdvertise(mySwitch: UISwitch) {
                let value = mySwitch.isOn
                // Do something
                print("switch value changed \(value)")
            }
        

        【讨论】:

          【解决方案6】:

          我在objective-c中有解决方法,是我经常使用的方法:

          -开关的Action必须在tableviewcontroller而不是cell上

          -当您点击动作内的开关时可以执行此操作以找到正确的单元格,然后您可以轻松找到索引或您需要的任何其他值...

          - (IBAction)switchValueChanged:(UISwitch *)sender
          {
              YourCellClass *cell = (YourCellClass *)[sender findSuperViewWithClass:[YourCellClass class]];
                  etc....
              }
          

          findSuperviewWithClass 方法是 UIView 上的一个类别

          - (UIView *)findSuperViewWithClass:(Class)superViewClass
          {
              UIView *superView = self.superview;
              UIView *foundSuperView = nil;
          
              while (nil != superView && nil == foundSuperView)
              {
                  if ([superView isKindOfClass:superViewClass])
                  {
                      foundSuperView = superView;
                  } else
                  {
                      superView = superView.superview;
                  }
              }
              return foundSuperView;
          }
          

          【讨论】:

            【解决方案7】:

            斯威夫特 3:

            @IBOutlet weak var mySwitch: UISwitch!  
            
            mySwitch.addTarget(self, action: #selector(MyClass.switchChanged(_:)), for: UIControlEvents.valueChanged)
            
            func switchChanged(_ mySwitch: UISwitch) {
                if mySwitch.isOn {
                    // handle on
                } else {
                    // handle off
                }
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2019-05-06
              • 2012-07-07
              • 1970-01-01
              • 2014-12-15
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多