在没有滚动的情况下在UIScrollView上添加视图(以编程方式)

时间:2017-08-18 22:11:39

标签: ios swift swift3 uiscrollview uipagecontrol

我正在尝试在我的UIScrollView Custom类之上添加页面控件。一切都很好。但每当我滑动scrollView时,页面控件也会沿着第一个图像滑动。

这是我的代码:

import Foundation
import UIKit
import SwiftyGif

class MBSPagingScrollView: UIScrollView {

var pageControl = UIPageControl()
var imagesArray = [String]()

override init (frame : CGRect) {
    super.init(frame : frame)
}

convenience init () {
    self.init(frame:CGRect.zero)
}

required init(coder aDecoder: NSCoder) {
    fatalError("This class does not support NSCoding")
}

init(frame : CGRect, imagesarray : [String]){
    super.init(frame : frame)

    imagesArray = imagesarray

    self.isPagingEnabled = true
    self.showsHorizontalScrollIndicator = false

    for (index, imageName) in imagesArray.enumerated() {

        var imageView = UIImageView()

        if imageName.hasSuffix(".gif") {
            let gifManager = SwiftyGifManager(memoryLimit:30)
            let gif = UIImage(gifName: imageName)
            imageView = UIImageView(gifImage: gif, manager: gifManager)
        }

        else {
            imageView = UIImageView(image: UIImage(named: imageName))
            imageView.contentMode = UIViewContentMode.scaleToFill
        }

        imageView.frame = CGRect(x: CGFloat(index) * self.frame.size.width, y: 0, width: self.frame.size.width, height: self.frame.size.height)
        self.addSubview(imageView)

    }

    self.contentSize = CGSize(width:self.frame.size.width * CGFloat(imagesArray.count),height: self.frame.size.height)

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

func configurePageControl() {
    self.pageControl.frame = CGRect(x: 0, y: self.frame.size.height - 50, width: self.frame.size.width, height: 50)
    self.pageControl.numberOfPages = imagesArray.count
    self.pageControl.currentPage = 0
    self.pageControl.tintColor = UIColor.red
    self.pageControl.pageIndicatorTintColor = UIColor.black
    self.pageControl.currentPageIndicatorTintColor = MainOrangeColor
    self.addSubview(pageControl)
}

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

func selfDidEndDecelerating(_ scrollView: UIScrollView) {
    let pageNumber = round(self.contentOffset.x / self.frame.size.width)
    pageControl.currentPage = Int(pageNumber)
}

}

以下是发生问题的图片

Page control is centered on the first image

enter image description here

正如您所看到的,页面控件正在与第一个图像一起滑动。我需要它留在中心。

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:2)

我认为你可以通过转到Storyboard来实现这一点,然后从UI Builder的左侧菜单中,将页面控件向下拖动并将其从滚动视图中拖出,如下图所示:

enter image description here

然后,您需要添加合适的约束以正确放置页面控件。

祝你好运!

答案 1 :(得分:0)

如果您不想滚动...请不要将其添加到滚动视图。

只需将页面控件添加到self.view,而不是滚动视图。