iOS UIPageControl

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

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

UIPageControl

UIPageControl继承自UIControl。
UIPageControl显示水平点,每个点对应于ViewController中的不同Page。

例如,UIPageControl用于浏览食物菜单的不同屏幕。

UIPageViewController用于浏览不同的页面,其中每个页面都是一个子视图控制器。

以下是UIPageControl类的一些属性和辅助函数。

  • currentPage:在UIPageControl中突出显示的当前页面。
    这将返回页面的索引。

  • numberOfPages:显示的页面数(等于点数)。

  • hidesForSinglePage:一个布尔值,用于切换PageControl在当前页面上的可见性。

  • pageIndicatorTintColor:当前页面上显示的色泽。

  • currentPageIndicatorTintColor:用于当前页面指示器的色彩颜色。

  • DefersCurrentPageDisplay:一个Bool值,控制何时显示当前页面。

  • updateCurrentPageDisplay():将页面指示符属性更新为当前页面。

当用户点击UIPageControl的左侧时,该用户将转到上一页。
当用户点击UIPageControl的右侧时,用户将转到下一页。

我们可以通过在Interface Builder中创建IBAction函数或者以编程方式使用选择器和目标来检测点击。
在本教程中,我们将坚持前一种方式。

每当您单击UIPageControl的左侧/右侧时,都会触发一次valueChanged事件。

在下一节中,我们将创建一个简单的iOS应用程序,当您更改页面时,其中Label文本和UIPageControl的背景也会更改。

以编程方式创建UIPageControl

let pageControl = UIPageControl()
      pageControl.frame = CGRect(x: 100, y: 100, width: 300, height: 300)
      pageControl.numberOfPages = 2;
      pageControl.currentPage = 0;
      view.addSubview(pageControl)

项目情节提要

您也可以在右侧属性检查器中设置属性。

在以上故事板上,

  • 我们已经将UIPageControl约束设置为屏幕宽度。

  • 在顶部添加了UILabel。

  • Ctrl +拖动UIPageControl在ViewController中创建一个插座

  • Ctrl +拖动UIPageControl在ViewController中创建IBAction。
    每当我们单击UIPageControl时,都会调用此方法。

  • Ctrl +拖动UILabel以在ViewController中创建IBOutlet。

ViewController.swift的代码如下所示:

import UIKit

class ViewController: UIViewController {

  @IBOutlet weak var myLabel: UILabel!
  
  @IBOutlet weak var myPageControl: UIPageControl!
  
  @IBAction func changePage(_ sender: UIPageControl) {
  
      myLabel.text = "Page \(sender.currentPage + 1)"
      
      switch sender.currentPage {
      case 0:
          sender.backgroundColor = UIColor.black
      case 1:
          sender.backgroundColor = UIColor.gray
      case 2:
          sender.backgroundColor = UIColor.orange
      default:
          sender.backgroundColor = UIColor.brown
      }
      
      
      
  
  }
  
  override func viewDidLoad() {
      super.viewDidLoad()
      
      myPageControl.numberOfPages = 4
      myPageControl.pageIndicatorTintColor = UIColor.yellow
      myPageControl.currentPageIndicatorTintColor = UIColor.blue
      
  }

}

我们已通过程序设置页面数和UIPageControl上的颜色。
每次单击UIPageControl并触发valueChanged事件时,标签和UIPageControl backgroundColor都会更改。