使用页面控件滚动视图以在 iOS 中显示图像

Scroll view with page control to display images in iOS

我正在尝试使用 Swift 实现带有页面控件的滚动视图以在 iOS 中显示图像,以获得如下输出:

这里的滚动视图是另一个视图控制器的一部分。 我用谷歌搜索但没有得到所需输出的帮助。 谁能帮帮我?

回答有点晚了。所以,可能对其他人有帮助:

Swift 3x:

首先,这样给代表团:

class YOUR_VIEW_CONTROLLER: UIViewController, UIScrollViewDelegate 

现在像这样连接 UIScrollViewUIPageControl 的插座:

@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var pageControl: UIPageControl!

NOTE:I'm using colours array. You can use image array instead.

var colors:[UIColor] = [UIColor.red, UIColor.blue, UIColor.green, UIColor.yellow]
var frame: CGRect = CGRect(x:0, y:0, width:0, height:0)

现在只需将以下代码复制并粘贴到您的 class:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    configurePageControl()

    self.view.bringSubview(toFront: pageControl)
    scrollView.delegate = self
    self.view.addSubview(scrollView)
    for index in 0..<4 {

        frame.origin.x = self.scrollView.frame.size.width * CGFloat(index)
        frame.size = self.scrollView.frame.size

        let subView = UIView(frame: frame)
        subView.backgroundColor = colors[index]
        self.scrollView.addSubview(subView)
    }

    self.scrollView.isPagingEnabled = true


    self.scrollView.contentSize = CGSize(width:self.scrollView.frame.size.width * 4,height: self.scrollView.frame.size.height)

    pageControl.addTarget(self, action: #selector(self.changePage(sender:)), for: UIControlEvents.valueChanged)

}

func configurePageControl() {
    // The total number of pages that are available is based on how many available colors we have.
    self.pageControl.layer.zPosition = 1

    self.pageControl.numberOfPages = colors.count
    self.pageControl.currentPage = 0
    self.pageControl.tintColor = UIColor.red
    self.pageControl.pageIndicatorTintColor = UIColor.black
    self.pageControl.currentPageIndicatorTintColor = UIColor.green
    self.view.addSubview(pageControl)

}

// MARK : TO CHANGE WHILE CLICKING ON PAGE CONTROL
func changePage(sender: AnyObject) -> () {
    let x = CGFloat(pageControl.currentPage) * scrollView.frame.size.width
    scrollView.setContentOffset(CGPoint(x:x, y:0), animated: true)
}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {

    let pageNumber = round(scrollView.contentOffset.x / scrollView.frame.size.width)
    pageControl.currentPage = Int(pageNumber)
}