UIScrollView图像偏离中心

时间:2018-01-13 07:32:40

标签: ios swift uiscrollview uipageviewcontroller

我正在使用UIPageController创建一个UIScrollView,我希望我的图像位于视图的中心,我将第一个图像直接放在中心,它工作正常。但是,当我滚动到下一页时,图像完全不在屏幕上。 enter image description here   second page

 @IBOutlet weak var pageControl: UIPageControl!

@IBOutlet weak var scrollView: UIScrollView!

override func viewWillAppear(_ animated: Bool) {
    navigationController?.setNavigationBarHidden(false, animated: true)
}


var contentWidth:CGFloat = 0.0

override func viewDidLoad() {
    super.viewDidLoad()
    let pageControl = UIPageControl.appearance()
    //Customizing
    pageControl.pageIndicatorTintColor = UIColor.black
    pageControl.currentPageIndicatorTintColor = UIColor.red
    scrollView.delegate = self

    for image in 0...2 {
        let imageToDisplay = UIImage(named: "\(image).png")
        let imageView = UIImageView(image: imageToDisplay)

        let xCoordinate = view.frame.midX + view.frame.width * CGFloat(image)
        let yCoordinate = view.frame.midY + view.frame.width * CGFloat(image)
        contentWidth += view.frame.width
        scrollView.addSubview(imageView)
        imageView.frame = CGRect(x: xCoordinate - 200, y: yCoordinate - 240, width: 400, height: 400)
    }

    scrollView.contentSize = CGSize(width: contentWidth, height: view.frame.height)
}

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    pageControl.currentPage = Int(scrollView.contentOffset.x / CGFloat(414))

}

0 个答案:

没有答案