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

时间:2016-07-29 11:16:06

标签: ios swift uiscrollview uipagecontrol

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

Required output

此处的滚动视图是另一个视图控制器的一部分。 我用谷歌搜索但没有得到任何帮助来获得所需的输出。 有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:2)

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

Swift 3x:

首先,给这样的代表团:

class YOUR_VIEW_CONTROLLER: UIViewController, UIScrollViewDelegate 

现在连接UIScrollViewUIPageControl的插座,如下所示:

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

注意:我使用的是颜色数组。您可以改为使用图像数组。

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

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

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)
}