1

Hello I am trying to create a side scroller with swift (I need to be compatible with IOS9 and I can not use UIScrollview.contentInsetAdjustmentBehavior = .never) and I am having trouble creating a UIScrollView which does not have a content inset. The following code shows what I did and I hope someone can point me to something.

override func viewDidLoad() {
        super.viewDidLoad()

        automaticallyAdjustsScrollViewInsets = false // 

        let someView = UIView()
        someView.frame = UIScreen.main.bounds
        someView.backgroundColor = .yellow
        view.addSubview(someView)

        // some image size calcs to keep the image in the same proportions on all devices.
        let frame = view.frame
        let height = frame.height * 0.35
        let ratioFactor = CGFloat(8.82)
        let width = height * ratioFactor

        let hillsImgView = UIImageView()
        let image = UIImage(named: "hills")
        hillsImgView.image = image

        // place imageView at the bottom of the screen
        let rect = CGRect(x: 0, y: frame.height - height, width: width, height: height)
        hillsImgView.frame = rect
        hillsImgView.backgroundColor = .green
        hillsImgView.contentMode = UIImageView.ContentMode.scaleToFill

        let hillsScrollView = UIScrollView()
        hillsScrollView.frame = UIScreen.main.bounds
        hillsScrollView.frame.origin.x = 10 // just to see the parent views yellow bg
        hillsScrollView.backgroundColor = .red
        hillsScrollView.contentSize = hillsImgView.frame.size // the image is longer then the screen
        hillsScrollView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0 right: 0)
        hillsScrollView.contentOffset = CGPoint(x: 0, y: 0)
        hillsScrollView.addSubview(hillsImgView)

        someView.addSubview(hillsScrollView)
    }

I can set the imageview x position to take away the SafeArea inset, but I feel like that's not a great solution either.

Cheers T.

Simulator result

TeeJaay
  • 136
  • 8
  • @DonMag Unfortunately this question has not been answered. I clearly stated that this needs to work in IOS9 the suggested answer is "only" working in later versions of iOS. – TeeJaay Jul 19 '20 at 22:19
  • @TeeJay - not sure what you mean by that... The first iPhone with Safe Area was the `iPhone X` with `iOS 11`. So, if your app's Deployment Target is `iOS 9`, you can use `if #available(iOS 11.0, *)` to use the `contentInsetAdjustmentBehavior` property. – DonMag Jul 20 '20 at 13:20
  • Yeah that makes sense. Thanks for the tip, I am fairly new to the ios ecosystem and I have still a few things to learn. Its a bummer we need to support ios9 at all but its a company decision and will ultimately lead to ugly inefficient code not to mention omitting all the great things you can use with later version. – TeeJaay Jul 20 '20 at 22:50

0 Answers0