Home UIScrollView image off center
Reply: 0

UIScrollView image off center

hg56 Published in 2018-01-13 07:32:40Z

I am creating a UIScrollView with a UIPageController and I want my images to be in the center of the view, I have the first image placed directly in the center and it works fine. However when I scroll to the next page the image is completely off screen.

 @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() {
    let pageControl = UIPageControl.appearance()
    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
        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))

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.293922 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO