如何将Pagecounter连接到ScrollView

时间:2019-07-18 17:40:52

标签: swift

试图将页面计数器连接到滚动视图,但是由于某些原因,滚动图像时它不会改变。

在滚动视图中计算图像尺寸变化的代码。


    @IBOutlet weak var myScrollView: UIScrollView!
    @IBOutlet weak var pageCounter: UIPageControl!

    var page = 0
    var myImages = [UIImage]()
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        var posX: CGFloat = 0
        let scrollWidth = myScrollView.frame.size.width
        let scrollHeight = myScrollView.frame.size.height
        myScrollView.isPagingEnabled = true
        myImages = [#imageLiteral(resourceName: "61763233_2273795276270684_2413481963462590464_o"), #imageLiteral(resourceName: "64431295_2284501085200103_3314220009403711488_n"), #imageLiteral(resourceName: "hrc1"), #imageLiteral(resourceName: "66263822_2295361957447349_1103112725925462016_n"), #imageLiteral(resourceName: "62022794_2274568069526738_785458383527346176_o")]
        view.setNeedsLayout()
        view.layoutIfNeeded()
        pageCounter.numberOfPages = myImages.count
        pageCounter.pageIndicatorTintColor = UIColor.gray
        pageCounter.currentPageIndicatorTintColor = UIColor.blue

        for img in myImages {
            let imgView = UIImageView(frame: CGRect(x: posX, y: 0, width: scrollWidth, height: scrollHeight))
            imgView.image = img
            imgView.contentMode = .scaleAspectFill
            imgView.clipsToBounds = true          
            myScrollView.addSubview(imgView)
            myScrollView.contentSize = CGSize(width: scrollWidth * CGFloat(myImages.count), height: scrollHeight)
            posX = posX + scrollWidth
        }
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let pageWidth = myScrollView.frame.size.width
        let getpage = round(myScrollView.contentOffset.x / pageWidth)
        let currentPage = Int(getpage)
        page = currentPage
        pageCounter.currentPage = page
    }

每次滚动后,页面计数器都应更改。

2 个答案:

答案 0 :(得分:0)

在ScrollView中设置PageCounter

示例:

其中 pageCounter 是您的对象, scrollView 是您的scrollView

NSLayoutConstraint.activate([
            pageCounter.topAnchor.constraint(equalTo: self.scrollView.topAnchor, constant: 15),
            pageCounter.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 30),
            pageCounter.heightAnchor.constraint(equalToConstant: 40),
            pageCounter.widthAnchor.constraint(equalToConstant: 40)
            ])

答案 1 :(得分:0)

“ myScrollview.delegate =自我”

此行代码丢失。使其无法与页面控件连接