Monday, April 1, 2019

Auto layout and Constraints in iOS

Layout is the way in which the UI components (UIView, UIButton, UILabel) are arranged together. Auto layout means the UI components dynamically change their sizes and positions according to external or internal changes such as the screen rotates. We have to define constraints for those UI components either in Interface Builder or programmatically so that they know how to change in different situations. For example, we can set a constraint for a button to always stay in the center of the screen both horizontally and vertically.

We must set enough constraints for each UI control added or we will get unexpected result like the control shows up in portrait mode but doesn't in landscape mode. 

How to know what constraints should be set? It's based on circumstances. Logically, the system must know the UI control's position and size so the constraint should tell enough information about the size and position. However, if we specify constraints for the top, leading, bottom, and trailing edges of an image view equal to its superview's, we don't have to specify its size because that's enough for the system to know its size. its size will always be the same as its superview's size.



Traditionally, without auto layout, the developers must calculate the size and position of a view's frame and its subview's frame. Then, when the screen's size changes, they have to recalculate the frame's sizes and positions for the view and its subviews.


Adding Constraints in Interface Builder


1). Drag a UIView object from the Object Library and drop it in the View Controller's view.


2). Control-drag the subview to the ViewController's view and select "Leading Space to Safe Area" from the popup.



Then, select the subview and open the Size Inspector and the leading constraint would appear there.


In my case, the leading space is 62 because I dropped the subview at that position. We can change it though by selecting the constraint in the Size Inspector and click Edit then update the Constant to 0 so that the subview's leading edge equal to the superview's leading edge.

3). Repeat Step 2 to set 3 more constraints for the subview by selecting "Top Space to Safe Area", "Trailing Space to Safe Area", and "Bottom Space to Safe Area" when the pop up appears. The image below shows the result of this step.



It's finished for our purpose here. The subview will dynamically change its size to maintain the defined spaces between its edges and the superview's.


Adding Constraints Programmatically


1). Control-drag the subview to the SecondViewController.swift in my case, to create an outlet so that we can access the subview from code


2). The constraints should be set in ViewController's viewDidLoaded() method as following:
    
import UIKit

class SecondViewController: UIViewController {
    
    @IBOutlet weak var view1: UIView!
    
    override func viewDidLoad() {
        view1.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
        view1.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
        view1.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
        view1.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
        view1.translatesAutoresizingMaskIntoConstraints = false
    }
}
    

The leadingAnchor, topAnchor, trailingAnchor, and bottomAnchor properties represent the leading, top, trailing, and bottom edges of the view's frame, respectively.

Note that if we have the constraints set both in Interface Builder and programmatically, the ones in Interface Builder take effect. If we want to programmatically modify the constraints defined in Interface Builder, we have to create the outlets connected the constraints from Interface Builder and modify them in viewDidLoad() method.

Layout Margins
We can define the constraints relative to the superview's margin instead. See here for more details.



Introduction to UIViewController

Normally, every app has at least one view controller (an instance of UIViewController class). Each view controller has one root view (an instance of UIView class). Commonly, one view controller manages one page.

View Controller's responsibilities:
- Updating the contents of the views
- Responding to user interactions with the views
- Resizing the views and managing the overall interface
- Coordinating with other objects, including other view controllers, in your app.

When creating Single View Application project, Xcode adds a view controller by default. The page or view that the view controller manages can be designed in the Storyboard (Main.storyboard file). For any additional setups for or actions to do responding to the user's interactions with the views in the page can be programmatically done in the corresponding ViewController.swift file. The ViewController class is connected to the view controller in the Storyboard through Class setting in Identity Inspector.



View Controller's Lifecycle


There are a bunch of methods, for example viewWillAppear(), are called according to its state. Usually, the property initializations are done in viewDidLoad() method. Note that any operations related to the view's or the subview's bounds property should be done in viewDidAppear() method because that's when the value of the bounds property is finalized. However, if there is a delay in the view rending and it does not look good to the user, the operations can be done in viewWillAppear() method instead but the layoutIfNeeded() method must be called first so that the system will layout any pending views and then you get the correct value of the bounds property.

Embedding A View Controller's Root View in Another View Controller's View


This post shows how to do it.




Thursday, March 28, 2019

Xcode eats up spaces (more than 10 GB)

Once in a while, I got prompted that my disk is running out of spaces. As I'm developing an iOS app using Xcode almost everyday, Xcode can be the culprit.

1). This step alone will claim several Gigabytes of disk space back.

> cd ~/Library/Developer/Xcode/DerivedData
> sudo rm -Rf *
    

2). Remove the oldest directories as many as possible
    
> cd ~/Library/Developer/Xcode/DerivedData/Devices
> ls -lh

total 24
drwxr-xr-x@ 4 vathanakmao  staff   136B Jul 21  2018 010C03D5-989F-4220-879E-023F62601A35
drwxr-xr-x@ 4 vathanakmao  staff   136B Jul 21  2018 05589345-6168-4338-9205-A42BF0C0A30C
drwxr-xr-x@ 5 vathanakmao  staff   170B Nov 27 11:13 0D1069CC-C10F-4D31-BB6E-62AF44C5107E
drwxr-xr-x@ 4 vathanakmao  staff   136B Jun 16  2017 0DF311E9-5E61-47CB-BBEA-6E8FEFC022C9
drwxr-xr-x@ 5 vathanakmao  staff   170B Nov 27 11:13 1115F8DE-BD11-4AD7-AC58-AC217D038CC5
drwxr-xr-x@ 4 vathanakmao  staff   136B Jun 26  2017 13145874-EE01-4E68-AA71-4912D6CF587F
drwxr-xr-x@ 4 vathanakmao  staff   136B Jun 26  2017 154CDEA7-17B5-4352-9603-FE8D6A788F2B
drwxr-xr-x@ 4 vathanakmao  staff   136B Dec 26  2016 15813813-54E7-4D77-8B2B-44B9C9105D73
drwxr-xr-x@ 4 vathanakmao  staff   136B Jul 21  2018 15A9EFFC-8718-4165-B3E9-C72F168511D6
drwxr-xr-x@ 4 vathanakmao  staff   136B Jul 21  2018 233E4A23-6956-4945-A7C8-86E6A7F1C1E5
drwxr-xr-x@ 4 vathanakmao  staff   136B Jun 16  2017 2B44F99E-858D-4AEC-BB3F-B816F27848D9
drwxr-xr-x@ 4 vathanakmao  staff   136B Jun 16  2017 2D27D8AE-26BC-423E-B6D7-7C327D9DA042
drwxr-xr-x@ 4 vathanakmao  staff   136B Jul 21  2018 2F6CEB95-74ED-489E-BBE3-AC8DFF766E79
...
    


References
https://stackoverflow.com/questions/36239242/xcode-7-3-taking-too-much-space

Tuesday, March 26, 2019

Introduction to UIView

A UIView is an object that manages the content for a rectangular on the screen. There are many kinds of view such as window, button, label and so on.

The bounds and frame properties


A UIView is initialized with a frame rectangle. The frame property, represented the frame rectangle, defines the view's size and position in its superview's coordinate system. The bounds property defines the view's size and position in its own coordinate system.


The bounds property is set to the frame property's value during the initialization. If the bounds changes, the frame changes too.


When to use them?

The frame property is used when resizing or moving the view in its superview. The bounds property is used to draw (set the position and size of) the view's content.

The layoutSubviews() method


The method is called whenever the bounds property changes so the developers should override this method to do any UI updates as needed. This method should not be called directly. If we need the view to layout its contents immediately, we should call either setNeededLayout() method or layoutIfNeeded() method.

The example below shows how to create a button with surrounding borders.
    
import Foundation
import UIKit

class BorderButton : CustomButton {
    
    @IBInspectable var inset:Bool = true {
        didSet {
            setNeedsLayout()
        }
    }
    
    @IBInspectable var bottomBorder: CGFloat = 1 {
        didSet {
            setNeedsLayout()
        }
    }
    
    @IBInspectable var rightBorder: CGFloat = 1 {
        didSet {
            setNeedsLayout()
        }
    }
    
    @IBInspectable var leftBorder: CGFloat = 1 {
        didSet {
            setNeedsLayout()
        }
    }
    
    @IBInspectable var topBorder: CGFloat = 1 {
        didSet {
            setNeedsLayout()
        }
    }
    
    @IBInspectable var borderColor: UIColor = UIColor.lightGray {
        didSet {
            setNeedsLayout()
        }
    }
    
    public override func layoutSubviews() {
        super.layoutSubviews()
        
        ViewUtil.setBorders(view: self, top: topBorder, bottom: bottomBorder, left: leftBorder, right: rightBorder, color: borderColor, inset: inset)
    }
}
    

Here is the complete codes of how to add a border to a view.


Layer (CALayer)


A view (UIView) contains at least one layer (CALayer). A CALayer object is responsible for drawing and animate the content. Any objects (UIView, UIButton, or UILabel) added to a UIView object (either in Interface Builder or programmatically) are drawn on the root layer by default.

Like UIView, CALayer also have frame, bounds, and backgroundColor properties. The values of those properties of a UIView object and its root CALayer object always match. Any changes on the view's property have effect on the matching property of the root layer.


Sub Layer 

The root layer of a view can have one or more sub layers. To add a sub layer, call UIView.layer.addSublayer() method. After adding a sub layer, any new objects you programmatically add to the view (by calling view.addSubview() method) are drawn on the sub layer. By default, the sublayer's backgroundColor property is nil and size is zero but its content still appear in the view. This is the purpose of the layer. If the sublayer and the root layer have the same frame's sizes and the sublayer's backgroundColor is set to yellow, for example, the root layer and its content completely disappear.



Layout Margins


A view has margins to define spaces between its content and its top, left, bottom, and right edges. For more details, go to this post.


Auto Layout and Constraints


A view can layout its contents dynamically (automatically) based on a predefined constraint. Go to this post for more details.


Monday, March 25, 2019

Highlight the selected cell in UICollectionView

This post is based on Xcode 9 and Swift 3. By default, when a user touches an item or a cell of a UICollectionView, some properties are updated and some events are triggered but there is no any UIs updated. It's the developer's job to update the UIs.

In the page below, there are a collection of themes displaying. When a user touches a theme, I want to show a green rectangle around it.


In the ViewController class, the UICollectionView.allowsMultipleSelection property should be set to false so that the user can select only one item/cell. When the user touches a cell, its isSelected property is set to true so the code to update the UIs for the cell should be done in the didSet block of the property as following:

class ThemeCollectionViewCell: UICollectionViewCell {
    ...
    
    @IBOutlet weak var rootStackView: UIStackView!
    
    override var isSelected:Bool {
        didSet {
            if isSelected {
                rootStackView.addBorders()
            } else {
                rootStackView.removeBorders()
            }
        }
    }
}
 

In case there is an item (cell) to be selected by default, the selectItem() method should be called in the ViewController.viewDidAppear() method to take effect then the isSelected property of the selected cell will be set to true.

Here is an example of how to add the borders to a stack view.

Add borders to a stackview

This post is based on Xcode 9 and Swift 3. I used UIStackView to divide the page into different sections with gray borders as shown in the image below.



I created a custom UIStackView class named BorderStackView as followings:
    
import Foundation
import UIKit

class BorderStackView : UIStackView {
    
    @IBInspectable var inset:Bool = true {
        didSet {
            setNeedsLayout()
        }
    }
    
    @IBInspectable var bottomBorder: CGFloat = 1 {
        didSet {
            setNeedsLayout()
        }
    }
    
    @IBInspectable var rightBorder: CGFloat = 1 {
        didSet {
           
            setNeedsLayout()
        }
    }
    
    @IBInspectable var leftBorder: CGFloat = 1 {
        didSet {
            setNeedsLayout()
        }
    }
    
    @IBInspectable var topBorder: CGFloat = 1 {
        didSet {
            setNeedsLayout()
        }
    }
    
    @IBInspectable var borderColor: UIColor = UIColor.lightGray {
        didSet {
            setNeedsLayout()
        }
    }
    
    public override func layoutSubviews() {
        super.layoutSubviews()
        
        ViewUtil.setBorders(view: self, top: topBorder, bottom: bottomBorder, left: leftBorder, right: rightBorder, color: borderColor, inset: inset)
    }
   
}
    

To remove a border, for example the top border, set topBorder property either programmatically or in Interface Builder to zero.

When the inset property is true, the borders are drawn inside the stackview's frame. Otherwise, they are drawn outside the frame.

And here is the body of the ViewUtil class:
    
import Foundation
import UIKit

class ViewUtil {
    private static let layerNameTopBorder = "topBorder"
    private static let layerNameBottomBorder = "bottomBorder"
    private static let layerNameLeftBorder = "leftBorder"
    private static let layerNameRightBorder = "rightBorder"
    
    static func setBorders(view: UIView, top topWidth: CGFloat, bottom bottomWidth: CGFloat, left leftWidth: CGFloat, right rightWidth: CGFloat, color: UIColor,inset:Bool = true) {
        var topBorderLayer:CALayer?
        var bottomBorderLayer:CALayer?
        var leftBorderLayer:CALayer?
        var rightBorderLayer:CALayer?
        for borderLayer in (view.layer.sublayers)! {
            if borderLayer.name == layerNameTopBorder {
                topBorderLayer = borderLayer
            } else if borderLayer.name == layerNameRightBorder {
                rightBorderLayer = borderLayer
            } else if borderLayer.name == layerNameLeftBorder {
                leftBorderLayer = borderLayer
            } else if borderLayer.name == layerNameBottomBorder {
                bottomBorderLayer = borderLayer
            }
        }


        // top border
        if topBorderLayer == nil {
            topBorderLayer = CALayer()
            topBorderLayer!.name = layerNameTopBorder
            view.layer.addSublayer(topBorderLayer!)
        }
        if inset {
            topBorderLayer!.frame = CGRect(x: view.bounds.minX, y: view.bounds.minY, width: view.bounds.width, height: topWidth)
        } else {
            topBorderLayer!.frame = CGRect(x: view.bounds.minX - leftWidth, y: view.bounds.minY - topWidth, width: view.bounds.width + leftWidth + rightWidth, height: topWidth)
        }
        topBorderLayer!.backgroundColor = color.cgColor


        // bottom border
        if bottomBorderLayer == nil {
            bottomBorderLayer = CALayer()
            bottomBorderLayer!.name = layerNameBottomBorder
            view.layer.addSublayer(bottomBorderLayer!)
        }
        if bottomWidth >= 0 {
            if inset {
                bottomBorderLayer!.frame = CGRect(x: view.bounds.minX, y:view.bounds.size.height - bottomWidth, width:view.bounds.size.width, height: bottomWidth)
            } else {
                bottomBorderLayer!.frame = CGRect(x: view.bounds.minX - leftWidth, y:view.bounds.size.height, width:view.bounds.size.width + leftWidth + rightWidth, height: bottomWidth)
            }
            bottomBorderLayer!.backgroundColor = color.cgColor
        }


        // left border
        if leftBorderLayer == nil {
            leftBorderLayer = CALayer()
            leftBorderLayer!.name = layerNameLeftBorder
            view.layer.addSublayer(leftBorderLayer!)
        }
        if inset {
            leftBorderLayer!.frame = CGRect(x: view.bounds.minX, y: view.bounds.minY, width: leftWidth, height: view.bounds.height)
        } else {
            leftBorderLayer!.frame = CGRect(x: view.bounds.minX - leftWidth, y: view.bounds.minY, width: leftWidth, height: view.bounds.height)
        }
        leftBorderLayer!.backgroundColor = color.cgColor


        // right border
        if rightBorderLayer == nil {
            rightBorderLayer = CALayer()
            rightBorderLayer!.name = layerNameRightBorder
            view.layer.addSublayer(rightBorderLayer!)
        }
        if inset {
            rightBorderLayer!.frame = CGRect(x: view.bounds.width - rightWidth, y: 0, width: rightWidth, height: view.bounds.height)
        } else {
            rightBorderLayer!.frame = CGRect(x: view.bounds.width, y: 0, width: rightWidth, height: view.bounds.height)
        }
        rightBorderLayer!.backgroundColor = color.cgColor
    }
    
}
    



Monday, March 18, 2019

Display images horizontally in a listbox with UICollectionView

I'm using Xcode 9 and swift 3 to developing a pet project. It requires showing a list of images horizontally at the bottom of the screen as shown in the image below.



1. Add UICollectionView in Interface Builder


- Drag UICollectionView from the Object Library and drop it on the View Controller and set appropriate constraints (related to its superview).

- Drag UIImageView from the Object Library and drop it on the UICollectionViewCell come with the UICollectionView object and set appropriate constraints related to the UICollectionViewCel. (Don't set constraints for the UICollectionViewCell)


2. Create a custom UICollectionViewCell class


- Select File menu > New > File...
- Select Cocoa Touch Class and click Next
- Set "Class" to ImageCollectionViewCell then "Subclass of" to UICollectionViewCell and make sure the "Also create XIB file" checkbox is unchecked cause we don't need it.

- Open ImageCollectionViewCell.swift file and create an outlet connected to the UIImageView control added in the step above.

import UIKit

class ImageCollectionViewCell: UICollectionViewCell {
        
    @IBOutlet weak var imageView: UIImageView!
}
 

- Within the storyboard, select the UICollectionViewCell control then open Identity Inspector and set Class under Custom Class section to ImageCollectionViewCell. After that, open Attributes Inspector and set Identifier under Collection Reusable View section to ImageCollectionViewCell.

3. Make the ViewController class conform to UICollectionViewDelegate and UICollectionViewDataSource


Create an outlet connected the UICollectionView control in the Interface Builder to the ViewController class and update it as following:


import Foundation
import UIKit

public class ViewController : UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
    
    @IBOutlet weak var collectionView: UICollectionView!
    
    private var images = [
        UIImage(named:"theme_1"),
        UIImage(named:"theme_2"),
        UIImage(named:"theme_3"),
        UIImage(named:"theme_4")
    ]
    
    public override func viewDidLoad() {
        collectionView.delegate = self
        collectionView.dataSource = self
    }
    
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return images.count
    }
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCollectionViewCell", for: indexPath) as! ImageCollectionViewCell
        cell.imageView.image = images[indexPath.row]
        return cell
    }
    
}
 

Note that any operations related to the sizes of cell's subviews should not be done in those methods of UICollectionViewCellDelegate because the frame and bounds properties are not finalized yet. Do it in layoutSubviews() method of the cell instead.

Setting the size of the cell in the method below does not have any effects.

public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
}
 


Setting the size of each cell and space between them


The ViewController must conform to UICollectionViewDelegateFlowLayout protocol and implement its methods.

The code snippets below is an example of how to set the size of a cell:

    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        // The height and width of the container view (stackview)
        // of the four buttons in the cell (xib file)
        // should be the same to make them look completely circles.
        // Then, the cell's width should be equal to cell's height
        // plus the tick buttons's width.
        // We have a constraint in the IB to define the tick button's width
        // equal to one-fourth width of the container view
        // so this size will fit them right.
        let cellHeight = collectionView.bounds.height - 10
        let tickButtonWidth = cellHeight / 4
        let cellWidth = tickButtonWidth + cellHeight
        return CGSize(width: cellWidth, height: cellHeight)
    }
 

This is an example of how to set the space between cell in the same row:

    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 25
    } 

The example below tells how to set the space between the collection view and its contents:
    
    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
    } 
    



References
https://www.youtube.com/watch?v=SL1ZmIp83iI