Wednesday, October 11, 2017

Setting background image for a table view in Swift

The UITableView has backgroundView and backgroundColor properties. You must set backgroundView property to nil if you want to set the background color of the table view. You can set the background view and background color for each cell of the table view too. The cell's backgroundView and backgroundColor properties have higher priorities than the table view's backgroundView and backgroundColor properties.

I'm using Xcode 8 and Swift 3 to develop this demo application. The goal is to set the background image for the table view. I have 3 different background images for different device's screen sizes. We divide the screen sizes into 3 different groups: 1x (for iPhone3G and priors), 2x (for iPhone4, 4s, 5, 5s, 6, 7, 8, and etc.), and 3x (for iPhone 6 Plus, 7 Plus, and 8 Plus). You can find more details here. The reason is the image could lose quality (has jagged edges or looks blur) when it scales down or up. We use one image for one group because there is no much difference between the screen sizes of the devices within the same group. It's ok to scale the image up or down a bit. The background images all have gray background but different texts in the center. The image below shows how it will look like.



1. Create background images for the device's groups

I used Photoshop to create 3 images with resolutions: 1242x2208 pixels (iPhone8 Plus), 750x1334 pixels (iPhone 8), and 320x480 pixels (iPhone 3G). I named them as background@3x.jpg, background@2x.jpg, and background@1x.jpg.

2. Add the background images to the app's bundle

- Open the project in Xcode and double click on Assets.xcassets file to open it in Assets Catalog Document
- Click on the plus sign at the bottom left corner and select New Image Set in the popup.
- Double click on the Image and rename it to background.
- Open Finder and drag the images to the assets catalog in Xcode. 


Note that if you run your application in iPhone 8 plus for example, the system uses 3x image. But if youO run it in iPhone 5 for example, the system use 2x image instead.

3. Set the table view's background image in code

Open the table view controller class and add the following codes to the viewDidLoad() method. In my project, the controller is called ItemViewsController.

let image = UIImage(named: "background", in: nil, compatibleWith: nil)
let imageView = UIImageView(image: image)
tableView.backgroundView = imageView

The background image won't show up because the table view's cell's background color has higher priority. In other words, the cells are in the front. You have to set the cell's background to transparent. It's simple by adding this line of code to the tableView(_:cellForRowAtmethod.

cell.backgroundColor = UIColor.clear







No comments:

Post a Comment