0

I am working on a swift app right now, that uses a table view to display news. For the background I set an image using the following line of code in the viewDidLoad method.

self.view.backgroundColor = UIColor(patternImage: UIImage(named: "backgroundImage.jpg")!)

however this makes the background repeat itself when scrolling down, which makes it look very ugly (see attached image).

Background image keeps repeating when scrolling

So what I desire is to have a fixed (non-repetitive) background image that always looks the same while scrolling and does not move at all.

How can I achieve that?

Thank you for your help!

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Marc Becker
  • 523
  • 2
  • 7
  • 18
  • You could add a `UIImageView` that is the same size as the `UIView` it is contained in. – Caleb Dec 21 '15 at 22:40
  • I tried this already, however it then covered the other elements and in addition it only had the screen size and therefore disappeared entirely when scrolling. Or do I have to give it some additional properties? – Marc Becker Dec 21 '15 at 22:43

2 Answers2

3

So I did some more digging and finally came across this post: https://stackoverflow.com/a/27684597/2204207

There it suggested to use

self.tableView.backgroundView = UIImageView(image: UIImage(named: "backgroundImage.png"))

instead of

self.view.backgroundColor = UIColor(patternImage: UIImage(named: "backgroundImage.png")!)

Therefore, when you want a fixed and non-repetitive background image use .tableView.backgroundView. This fixes the background images even when scrolling down.

Community
  • 1
  • 1
Marc Becker
  • 523
  • 2
  • 7
  • 18
0

You can make a view hierarchy like this.

enter image description here

Make ImageView and TableView as same size and place table view below the ImageView in view navigator.

Then add your background image to the ImageView and make TableView's background to clear color.

Emma
  • 8,518
  • 1
  • 18
  • 35
  • Hey thanks for your reply! Unfortunately my TableView is a direct child of the ViewController (so without a "View" in-between). Therefore I can't make the image a sibling of the tableview, do you have an idea how to overcome this? – Marc Becker Dec 21 '15 at 23:15
  • Cannot use ViewController instead of TableViewController for your need ? Refactoring to TableView inside of ViewController is a bit of work but I think this is easier and will give you a reliable outcome. – Emma Dec 21 '15 at 23:28
  • Thanks for your help, I now found a way to fix the background image using a TableViewController and posted the answer above. Nevertheless thank you for your help! – Marc Becker Dec 22 '15 at 13:33