iOS UISwitch

时间:2020-02-23 14:45:58  来源:igfitidea点击:

在本教程中,我们将在iOS应用程序中讨论和实现UISwitch控件。

UISwitch

UISwitch就像一个切换按钮,具有两种状态:开和关。
UISwitch控件通常用于需要启用或者禁用某些功能的地方。

  • var isOn:Bool
  • func setOn(Bool,animation:Bool)

第一个是属性,用于检查状态。
第二个是用于设置UISwitch状态的函数。

要以编程方式创建UISwitch:

func createSwitchProgrammatically() {
  let mySwitch = UISwitch(frame:CGRect(x: 150, y: 150, width: 0, height: 0))
  mySwitch.isOn = false
  self.view.addSubview(mySwitch)
      
}

与许多其他UI控件类似,当Switch状态更改时,会触发" valueChanged",我们可以在选择器中进行观察。

以下是自定义UISwitch的重要属性和功能:

  • var onTintColor:UIColor?–开关打开时的颜色。

  • var tintColor:UIColor!–开关关闭时的轮廓颜色

  • var thumbTintColor:UIColor?– UISwitch的拇指的淡色

  • var onImage:UIImage?– iOS 10中已弃用。

  • var offImage:UIImage?– iOS 10中已弃用。

建议使用UISwitch的标准大小。

在下一部分中,我们将创建一个应用程序,该应用程序实现自定义UISwitch并处理状态。

项目情节提要

我们可以在属性检查器中设置UISwitch的初始状态。

按住Control键并将箭头从UISwitch拖动到在属性检查器中找到的ViewController.swift中,以添加操作:

代码

下面给出了ViewController.swift的代码:

import UIKit

class ViewController: UIViewController {

  @IBOutlet weak var customSwitch: UISwitch!
  @IBOutlet weak var myLabel: UILabel!
  override func viewDidLoad() {
      super.viewDidLoad()
      //Do any additional setup after loading the view, typically from a nib.
      
      customSwitch.tintColor = UIColor.blue
      customSwitch.thumbTintColor = UIColor.black
      customSwitch.onTintColor = UIColor.brown
      
      createSwitchProgrammatically()
  }
  
  func createSwitchProgrammatically() {
      let mySwitch = UISwitch(frame:CGRect(x: 150, y: 150, width: 0, height: 0))
      mySwitch.isOn = false
      mySwitch.addTarget(self, action: #selector(self.stateChanged), for: UIControl.Event.valueChanged)
      self.view.addSubview(mySwitch)
      
  }

  @IBAction func switchOnValueChanged(_ sender: Any) {
      myLabel.text = "Is on? \((sender as! UISwitch).isOn)"
  }
  
  @objc func stateChanged(mySwitch: UISwitch)
  {
         myLabel.text = "Programmatic switc Is on? \(mySwitch.isOn)"
  }
}

stateChanged方法是为以编程方式创建的UISwitch创建的自定义选择器。
我们在UILabel上显示每个UISwitch的当前状态。

如您所见,UILabel成功检测到两个UISwitch上的更改。