Make App Pie

Training for Developers and Artists

Tips: Tricks with Asset Manager

iOS Development tips weekly is a series you can find at the Lynda.com and LinkedIn Learning libraries. The first week of a week’s tip will be available for free. After that, you will need a subscription to get access to it. Click the image at left  to view.  You’ll find an amended transcript below.

One feature that has been around for a while, but may not get the respect it needs is the asset manager. Found on the folder assets.xcassets,  the asset manager organizes assets. Most of us have run into this for images and everyone has to use the app icon here, but that’s just one thing you can do with assets. There a whole lot more. Let’s look at images and two more: colors and data.

Adding Assets

May of you already know how to quickly add images to asset folder, but let me review. Before you add the image you change the file names to specify the size. I have a starter project folder for this project. Download the file. In the assets folder in the download, you’ll find a folder named images. Notice I added @2X and @3x to some of these images.

By appending this to the file name, Xcode can figure out what are the 1x, 2,x and 3x images. I can select all of these, and drag them into the assets, and everything organizes, including the name of the file.

The newest use of assets is adding color constants. This gives you a standard palette to use through your app. Hit the + and add a color set.

 

A blank square appears

Click on the square, and change the color on the attributes inspector using the color space and input method you find useful.

 

I’ll stay with sRGB. You have different color input methods.

I tend to use  8-bit hex.  This replaces the sliders with a text box.

I’ll add  a light blue #ddddff and name it at top Light Blue.

I’ll  repeat the process to make Pale Yellow the same way with #ffffdd

 

In the assets list, you’ll now find the two colors.

 

One last type I’ll show you is data. You can store just about everything else such as settings and reference documents in the assets manager if you don’t want to use the bundle or filesystem. In the downloaded assets folder, I  have a comma separated file breakfast here of breakfast foods.

I can open it in TextEdit to see it is a string separated by commas.

I’ll make a new data set. I’ll just drag it from the finder to the assets manager. It used the file name breakfast as the asset name.

Using Asset Manager in Code

In code, all uses of the asset manager will have a String parameter named. Open the ViewController.swift file.  I set up a table view here and I can get the small image into the table cell image view  by adding this just under the textLabel line:

cell.imageView?.image = UIImage(named: breakfastStuff[row] + " small")

When the cell is selected, it sets the destination controller’s title to the breakfast food selected. I’ll  add the large image on that destination file,  DisplayViewController.swift on an image view I set there in viewDidLoad.

imageView.image = UIImage(named: title!)

Colors work the same way.  Go back to tableView(_ tableView: cellForRowAt IndexPath).  The code is alternating colors between yellow and blue. I can change to named colors instead

if row % 2 == 0 {
    cell.backgroundColor = UIColor(named: "Light Blue")
} else {
    cell.backgroundColor = UIColor(named: "Pale Yellow")
}

I’ll use the data to be my list of breakfast stuff for the table view, which is defined as breakfastStuff. For data, you use the NSDataAsset object to get the asset. In viewDidLoad I’ll unwrap the data asset

if let dataAsset = NSDataAsset(name: " breakfast"){

If it exists, I’ll use its  data property to get the data and convert data to a String array like this.

let string = String(data: dataAsset.data, encoding: .utf8)
breakfastStuff = (string?.components(separatedBy: ","))!

Colors by the way will show up on the storyboard color selections. Go to the storyboard. Select the table view, and select the drop down for the background color. You’ll see your defined colors, making it simple to keep your palette straight. I’ll select the Light Blue.

Run this. You’ll get the table with all four breakfast foods.

tap a food and you get the big photo.

As you can see, with only a little code and some planning, assets become a great way to organize your images, colors and data.

The Whole Code

You can download the completed project from GitHub. Here is the code for the project

ViewController.Swift

//
//  ViewController.swift
//  BreakfastTable
//
//  Created by Steven Lipton on 12/4/17.
//  Copyright © 2017 Steven Lipton. All rights reserved.
//

import UIKit

class ViewController: UITableViewController {

    
    var breakfastStuff = ["French Toast","Pancakes"]

    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return breakfastStuff.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        let row = indexPath.row
        cell.textLabel?.text = breakfastStuff[row]
        cell.imageView?.image = UIImage(named: breakfastStuff[row] + " small")
        if row % 2 == 0 {
            cell.backgroundColor = UIColor(named: "Light Blue")
        } else {
            cell.backgroundColor = UIColor(named: "Pale Yellow")
        }
        return cell
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let row = indexPath.row
        let displayVC = DisplayViewController()
        displayVC.title = breakfastStuff[row]
        navigationController?.pushViewController(displayVC, animated: true)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "Breakfast"
        if let dataAsset = NSDataAsset(name:"breakfast"){
            let string = String(data: dataAsset.data, encoding: .utf8)
            breakfastStuff = (string?.components(separatedBy: ","))!
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}


DisplayViewCOntroller.swift

//
//  DisplayViewController.swift
//  BreakfastTable
//
//  Created by Steven Lipton on 12/4/17.
//  Copyright © 2017 Steven Lipton. All rights reserved.
//

import UIKit

class DisplayViewController: UIViewController {
    
    var imageView = UIImageView()
    override func viewDidLoad() {
        super.viewDidLoad()
        imageView.frame = view.frame
        imageView.contentMode = .scaleAspectFill
        imageView.image = UIImage(named:title!)
        view.addSubview(imageView)
    }
}

One response to “Tips: Tricks with Asset Manager”

  1. […] UIColor. That was a function you had to copy and paste into your code. I’ve also shown you how to use the assets to keep color names handy. What would be even better is to do all that directly from UIColor. For that you uses […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: