iOS UISegmentedControl

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

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

UISegmentedControl

UISegmentedControl是由离散按钮组成的水平条。
当单击每个按钮时,这些按钮用于显示/隐藏内容或者显示不同的内容。

这样,每个按钮负责屏幕上的不同段。

以下是UISegmentedControl的辅助函数:

  • setImage(UIImage ?, forSegmentAt:Int):在分段控件上的给定位置设置图像。

  • imageForSegment(at:Int):返回特定段的图像

  • setTitle(String ?, forSegmentAt:Int):在标题位置设置标题。

  • titleForSegment(at:Int):返回指定段位置的标题。

  • insertSegment(withTitle:String ?, at:Int,animation:Bool):在UISegmentControl中的特定位置插入一个段并设置一个标题。

  • removeAllSegments():从UISegmentControl中删除所有细分按钮

  • setEnabled(Bool,forSegmentAt:Int):在指定位置启用细分。

  • isEnabledForSegment(at:Int):返回指定段是否启用。

  • setWidth(CGFloat,forSegmentAt:Int):设置细分控件指定细分的宽度。

还有一些属性,例如" tintColor"," numberOfSegments"。
这些是不言自明的。

默认情况下,UISegment控件中的段具有相等的宽度。
有时,SegmentedControl中的特定Segment可以具有更长的标题。
这将挤压标题内容。

为了创建具有不同宽度的线段,我们可以在每个线段上使用setWidth函数,或者使用:

segmentedControl.apportionsSegmentWidthsByContent = true

在下一节中,我们将使用简单的iOS应用程序创建一个新的XCode项目,该应用程序展示了UISegmentedControl的不同用例。

项目情节提要

在右侧的"属性"检查器中,我们可以向UISegmentedControl中添加更多细分。

我们已经将UISegmentedControl的IBOutlet添加到ViewController文件中。
每当在UISegmentedControl中单击其他细分时,都会触发IBAction。

由于它与iOS中的其他UI控件相当普遍,因此触发了" valueChanged"事件以执行IBAction函数。

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

import UIKit

class ViewController: UIViewController {

  @IBOutlet weak var segmentControl1: UISegmentedControl!
  @IBOutlet weak var segmentedControl2: UISegmentedControl!
  @IBOutlet weak var labelOne: UILabel!
  @IBAction func segmentControlAction(_ sender: Any) {
      let sControl = sender as! UISegmentedControl
      
      if sControl.tag == 101
      {
          sControl.backgroundColor = UIColor.brown
          labelOne.text = sControl.titleForSegment(at: sControl.selectedSegmentIndex)
      }
      else{
          sControl.backgroundColor = UIColor.black
          
          if sControl.selectedSegmentIndex == 0
          {
          sControl.tintColor = UIColor.red
          sControl.insertSegment(withTitle: "New", at: sControl.numberOfSegments-1, animated: true)
          }
          else{
          sControl.tintColor = UIColor.orange
          }
          labelOne.text = sControl.titleForSegment(at: sControl.selectedSegmentIndex)
      }
  }
  
  override func viewDidLoad() {
      super.viewDidLoad()
      segmentedControl2.selectedSegmentIndex = 1
      segmentedControl2.apportionsSegmentWidthsByContent = true
      segmentControl1.tag = 101
  }

}

在上面的代码中,每个UISegmentedConrol连接到相同的IBAction。
我们在viewDidLoad方法的其中一个控件上设置了标签。

在IBAction内部,我们检查是否单击了UISegmentedControl,并更改了标签文本以及UISegmentedControl的tintColor,如下面的输出所示。