OUR BLOG

21 Dec 2020

iOS swift 开发中 Scroll Page Image 的演示代码

iOS swift 开发中 Scroll Page Image 的演示代码 多个图片可以左右滑动查看的代码

import UIKit

class ViewController: UIViewController, UIScrollViewDelegate {

let scrollView = UIScrollView(frame: CGRect(x:0, y:0, width:UIScreen.main.bounds.width,height: UIScreen.main.bounds.width))

var colors:[UIColor] = [UIColor.red, UIColor.blue, UIColor.green, UIColor.yellow]

var frame: CGRect = CGRect(x:0, y:0, width:0, height:0)

var pageControl : UIPageControl = UIPageControl(frame: CGRect(x:0,y: UIScreen.main.bounds.width, width:UIScreen.main.bounds.width, height:50))

override func viewDidLoad() {

super.viewDidLoad()

// Do any additional setup after loading the view.

super.viewDidLoad()

scrollView.delegate = self

scrollView.isPagingEnabled = true

scrollView.showsVerticalScrollIndicator = false

scrollView.showsHorizontalScrollIndicator = false

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.contentSize = CGSize(width:self.scrollView.frame.size.width * 4,height: self.scrollView.frame.size.height)

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

configurePageControl()

}

func configurePageControl() {

// The total number of pages that are available is based on how many available colors we have.

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

@objc 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)

}

}

admin