我应该如何使用UIScrollView中的UIpageControl

时间:2017-04-28 08:19:38

标签: ios iphone swift uiscrollview uipagecontrol

我应该如何使用UIpageControl中的UIScrollView,我被困住帮帮我

这是我的代码请帮助

class home: UIViewController, UIScrollViewDelegate {

    @IBOutlet weak var mainScrollView: UIScrollView!
    @IBOutlet weak var pagecontrol: UIPageControl!

    var imageArray = [UIImage]()
    var pageControl : UIPageControl!

    override func viewDidLoad() {
        super.viewDidLoad()


        mainScrollView.delegate = self

    imageArray = [#imageLiteral(resourceName: "sliderImage"), #imageLiteral(resourceName: "clothing"), #imageLiteral(resourceName: "sports")]

        for i in 0..<imageArray.count{

            let imageView = UIImageView()
            imageView.image = imageArray[i]
            imageView .contentMode = .scaleToFill
            let xPosition = self.view.frame.width * CGFloat(i)
            imageView.frame = CGRect(x: xPosition, y: 0, width: self.mainScrollView.frame.width, height: self.mainScrollView.frame.height)

            mainScrollView.contentSize.width = mainScrollView.frame.width * CGFloat(i + 1)
            mainScrollView.addSubview(imageView)
        }


        // Do any additional setup after loading the view.
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

1 个答案:

答案 0 :(得分:1)

检查答案stackoverflow.com/a/20504797/1531141

这些年来情况几乎相同:

  1. 将您的uiscrollview委托设置为您的视图控制器(您所做的)
  2. 为scrollViewDidScroll委托方法添加代码:
  3. func scrollViewDidScroll(_ scrollView:UIScrollView)

    {
    
        self.pageControl.currentPage = Int(floorf(Float(scrollView.contentOffset.x / scrollView.width)))
    }    
    
    1. 在scrollViewDidEndDecelerating方法中添加相同的内容:

      func scrollViewDidEndDecelerating(_ scrollView:UIScrollView)

      {
          self.pageControl.currentPage = Int(floorf(Float(scrollView.contentOffset.x / scrollView.width)))
      }
      
    2. 虽然,这取决于您的需求 - 尝试如何使用和不使用其中一个