Saturday, July 27, 2019

Introduction to a property list with Swift

What is a property list?


A property list is a file system with the extension plist, which represents an object graph.


When to use it?


It's portable and efficient to store a small amount of data. It should not be used to store a complex object graph. If the data is not likely to change, should we hard-code (store the data with the source code) it instead? For best practices, data should be stored separately from the source code because it's less error prone and we don't need to recompile the program every time when we change the data.


Reading a property list into an array (of a dictionary)


    private var _decimalPlaces:[DecimalPlace] = []
    var decimalPlaces:[DecimalPlace] {
        get {
            if _decimalPlaces.isEmpty {
                do {
                    let dp = try loadAsArray(filename: "DecimalPlaces", format: .xml)
                    _decimalPlaces = toDecimalPlaces(dp)
                } catch {
                    fatalError("Failed to load decimal places from property list file.")
                }
            }
            return _decimalPlaces
        }
    }
    
    func loadAsArray(filename: String, format: PropertyListSerialization.PropertyListFormat = .xml) throws -> [AnyObject] {
        var result:[AnyObject] = []
        if let path = Bundle.main.path(forResource: filename, ofType: "plist") {
            if let xml = FileManager.default.contents(atPath: path) {
                var plistFormat = format
                result = try PropertyListSerialization.propertyList(from: xml, options: .mutableContainersAndLeaves, format: &plistFormat) as! [AnyObject]
            }
        }
        return result
    }
    
    private func toDecimalPlaces(_ src:[AnyObject]) -> [DecimalPlace] {
        var result:[DecimalPlace] = []
        for i in 0..

The source code above works with the property list file, DecimalPlaces.plist, with the contents below. It's in the root directory of the project like Info.plist file.


Below is the content of DecimalPlace class:
    
class DecimalPlace {
    var id:Int!
    var value:UInt?
    var label:String!
    var description:String!
    
    init() {       
    }
}
    


Reading a property list into a dictionary


    func load(filename: String, format: PropertyListSerialization.PropertyListFormat = .xml) throws -> [String:AnyObject] {
        var result:[String:AnyObject] = [:]
        if let path = Bundle.main.path(forResource: filename, ofType: "plist") {
            if let xml = FileManager.default.contents(atPath: path) {
                var plistFormat = format
                result = try PropertyListSerialization.propertyList(from: xml, options: .mutableContainersAndLeaves, format: &plistFormat) as! [String:AnyObject]
            }
        }
        return result
    }
    

The code snippets above works with the property list file with the contents below:






References
https://developer.apple.com/library/archive/documentation/General/Conceptual/DevPedia-CocoaCore/PropertyList.html

Thursday, July 18, 2019

Embedding a view controller's root view in another view controller's view

We can add a view controller's root view to another view controller's view for reusability purpose.


We can programmatically add a view controller's root view to a subview of another view controller as following:

public class ThemesViewController : UIViewController {

 @IBOutlet weak var previewView: UIStackView!
 var vcMain:ViewController!

 ...

 public override func viewDidLoad() {
   vcMain = storyboard?.instantiateViewController(withIdentifier: "vcMain") as! ViewController
 } 
 
 public override func viewWillAppear(_ animated: Bool) {
                // The system does not wait until each view in the hierarchy
                // has updated its layout before calling the viewWillAppear() method
                // so some subviews still have incorrect bounds
                // and will change in viewDidAppear() method.
                // Calling layoutIfNeeded() method forces the previewView to
                // update its layout immediately so we get the correct bounds here.
                previewView.layoutIfNeeded()   
        
                self.addChildViewController(vcMain)
  previewView.addSubview((vcMain.view)!)
  vcMain.didMove(toParentViewController: self)
 }
}
    

The addChildViewController() method calls the willMove(toParentViewController:) of the child view controller for us so we can override the method and do more things if needed.

The didMove(toParentViewController: self) method of the child view controller have to be called after the child view controller's root view has been added to the parent view controller's view and any necessary constraints between the views have been defined. This method gives the chance to the child view controller to perform any actions if needed, responding to the change in view ownership (by overriding the method). Note that my project still worked correctly even if I didn't call didMove(toParentViewController:) method.

In my case, the size and position of the previewView were already set in the Interface Builder so I don't have to programmatically create constraints for the previewView, after calling previewView.addSubview((vcMain.view)!) as mentioned here.


Monday, July 8, 2019

Introduction to User's Defaults Database

To store user's preferences in an app, we can use the user's defaults database, which will be created by the system on each device (iOS or Mac OS) by the time we access it. Note that the database is not suitable for large data and heavy transactions. Preferences are grouped into domains. There are 5 different types of domains:
1). The argument domains (UserDefaults.argumentDomain): Volatile
2). Application (identified by the app's identifier, for example, com.vathanakmao.MyCalculator): Persistent, should be used by their corresponding apps.
3). The global domains (UserDefaults.globalDomain): Persistent, used by system frameworks and accessed by different apps.
4). The languages domains: Volatile
5). The registration domain (UserDefaults.registrationDomain): Volatile

The lifetime of a preference depends on the domain, in which it is stored in. Some domains store preferences persistently, which means that the preferences continue to exist across app launches. Some others store preferences in more volatile way (shorter life), keeping preference values only for the life of the corresponding user defaults object (the user defaults object may be destroyed by the system or when the app exits).

For example, calling UserDefaults.standard.register(default: [String, Any]) method stores the preference dictionary object in the registration domain, and the object is deleted when the app exits. We can test it while in development by adding the code in the AppDelegate class and run the project in the simulator from Xcode. After that, quit the simulator and remove the code from the AppDelegate then run the project again. In contrast, calling the UserDefaults.standard.set(_,forKey)method stores the preference object persistently, which means that the object can still be accessed in the next sub sequent project launches even if after the method call is removed.

Storing value


UserDefaults.standard.set(1000, forKey: "item1")
    

It's recommended that the value should be as simple as possible for better performance even though the Data type is supported. The value of a primitive type would be ideal.

Getting value


UserDefaults.standard.integer(forKey: "item1")
    

If the object does not exist, the returned value falls back to the default value of its corresponding type. It would be 0 (zero) in the case above (, and false in case it's Bool)

The system searches for the key in all domains one by one based on their orders listed above until the key is found.

Registering default value for certain key


For example, calling UserDefaults.standard.integer(forKey) method on non-existent key would return 0 (zero), but 0 is meaningful in our case and we want it to return a different number like -1 (minus one). We should register the default value for that key in AppDelegate class as following:
    
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
 let preferences = ["item1", -1]
 UserDefaults.standard.register(defaults: preferences)
}
    



References
https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/UserDefaults/AboutPreferenceDomains/AboutPreferenceDomains.html#//apple_ref/doc/uid/10000059i-CH2-SW6

Thursday, April 4, 2019

Animation: moving contents with constraints in Swift

I'm developing a pet project, named MyCalculator, using Swift 3. In portrait mode, the app shows only the basic operation buttons but when the user swipes to right, the basic operation buttons should slide out and the advance operation buttons should slide in as shown in the image below.


I put the basic operation buttons in one stackview and the advanced operation buttons in another stackview. Then, I put those two stackviews in another stackview together, named Buttons Stack View. I added two constraints for the Buttons Stack View to define its leading edge and trailing edge equal to the ViewController's view's leading edge and trailing edge, respectively.


To make the basic operation buttons disappear and the advanced operation buttons appear, I changed to constant property of the constraint as following:

self.buttonsStackviewLeading.constant = self.buttonsStackviewLeading.constant + view.bounds.width
self.buttonsStackviewTrailing.constant = self.buttonsStackviewTrailing.constant + (-1 * view.bounds.width)
    
But, I want to do more than that. i want to container stackview of those buttons move according to the user's finger movement point by point. This requires more effort and I put it in the steps below.

1. Create required outlets 


Create outlets for the Buttons Stack View and it's leading and trailing constraints as following:

    @IBOutlet weak var buttonsStackView: UIStackView!
    @IBOutlet weak var buttonsStackviewLeading: NSLayoutConstraint!
    @IBOutlet weak var buttonsStackviewTrailing: NSLayoutConstraint!
    

2. Initializing UIPanGestureRecognizer 


- Add the following lines to the ViewController's viewDidLoad() method.

let panGestureRecognizer = UIPanGestureRecognizer()
panGestureRecognizer.addTarget(self, action: #selector(panGestureHandler(_:)))
buttonsStackView.addGestureRecognizer(panGestureRecognizer)
    

3. Handle the Pan Gesture Recognizer

Add these properties to the ViewController

    private var beganPoint:CGPoint?
    private var previousPoint:CGPoint?
    private var beganStackviewFrameMinX:CGFloat?
    private var beganStackviewFrameMaxX:CGFloat?
    private static let swipeFastMinPointsPerSecond = CGFloat(400)
    private static let maxPointsToMoveWhenSwipeFast = CGFloat(20)
    

Then add the following method:

    @objc public func panGestureHandler(_ recognizer:UIPanGestureRecognizer) {
        // Don't use UIDevice.current.orientation.isLandscape here
        // because its value can be 'flat (face-up or face-down)'
        // then the user would still be able to swipe when the app's UI is in landscape.
        if UIApplication.shared.statusBarOrientation.isLandscape {
            return
        }
        
        let currentPoint = recognizer.translation(in: view)
        let halfScreenWidth = view.bounds.width / 2
        
        if recognizer.state == .began {
            previousPoint = currentPoint
            beganStackviewFrameMinX = buttonsStackView.frame.minX
            beganStackviewFrameMaxX = buttonsStackView.frame.maxX
        } else if recognizer.state == .changed {            
            var changedPointsDiff = currentPoint.x - (previousPoint?.x)!
            previousPoint = currentPoint
            
            if swipedFast(recognizer) {
                changedPointsDiff = recognizer.velocity(in: view).x < 0 ? (-1 * ViewController.maxPointsToMoveWhenSwipeFast) : ViewController.maxPointsToMoveWhenSwipeFast
            }
            
            // If in case like the basic buttons are showing
            // and the user swipes/drags from right to left,
            if beganStackviewFrameMinX! == view.bounds.minX && buttonsStackviewLeading.constant > halfScreenWidth
                || beganStackviewFrameMaxX! == view.bounds.maxX && buttonsStackviewTrailing.constant > halfScreenWidth {
                
                // so the user can't drag those buttons more than half the screen
                return
            }
            
            buttonsStackviewLeading.constant = buttonsStackviewLeading.constant + changedPointsDiff
            buttonsStackviewTrailing.constant = buttonsStackviewTrailing.constant + (-1 * changedPointsDiff)
        } else if recognizer.state == .ended {
            
            let totalPointsMoved = buttonsStackView.frame.minX - beganStackviewFrameMinX!
            var finalPointsToMove:CGFloat = -1 * totalPointsMoved // Should move back to original position by default

            let swipedPointsPerSecond = recognizer.velocity(in: view).x
            if swipedFast(recognizer) {
                
                // When the user swipes fast, slide in advanced buttons or basic buttons.
                // It doesn't have to be a long swipe/drag.
                if beganStackviewFrameMinX! == view.bounds.minX && swipedPointsPerSecond < 0 {
                    finalPointsToMove = -1 * view.bounds.width - totalPointsMoved
                } else if beganStackviewFrameMaxX! == view.bounds.maxX && swipedPointsPerSecond > 0 {
                    finalPointsToMove =  view.bounds.width - totalPointsMoved
                }
            } else if beganStackviewFrameMinX == view.bounds.minX && totalPointsMoved > 0
                || beganStackviewFrameMaxX == view.bounds.maxX && totalPointsMoved < 0
                || abs(totalPointsMoved) < halfScreenWidth {
                
                // If the basic buttons are showing and the user swiped to left,
                // just move them to left a little bit and then move them back to the original position.
                finalPointsToMove = -1 * totalPointsMoved
            } else if abs(totalPointsMoved) > halfScreenWidth {
                
                // If dragged more than half the screen width,
                // show advanced/basic buttons
                finalPointsToMove = view.bounds.maxX - abs(totalPointsMoved)
                finalPointsToMove = totalPointsMoved > 0 ? finalPointsToMove : -1 * finalPointsToMove
            }
            
            self.buttonsStackviewLeading.constant = self.buttonsStackviewLeading.constant + finalPointsToMove
            self.buttonsStackviewTrailing.constant = self.buttonsStackviewTrailing.constant + (-1 * finalPointsToMove)
            UIView.animate(withDuration: 0.3, animations: {
                self.view.layoutIfNeeded()
            }, completion: {(finished:Bool) in
                if finished {
                    if self.buttonsStackviewLeading.constant >= 0 {
                        self.showedAdvancedOperationsInPortrait = true
                    } else {
                        self.showedAdvancedOperationsInPortrait = false
                    }
                }
            })
        }
    }
    

And add this helper method too

    private func swipedFast(_ recognizer:UIPanGestureRecognizer) -> Bool {
        return abs(recognizer.velocity(in: view).x) > ViewController.swipeFastMinPointsPerSecond
    }
    

The recognizer.velocity() method below returns the number of points per second in which the user has swiped the screen. The amount of points the user has swiped across the screen might be only 30 but the velocity might be 3000 points per second.


Note (AffineTransform)


We can also use AffineTransform struct to move the buttons as following:
    
buttonsStackView.transform = buttonsStackView.transform.translatedBy(x: pointsToMove, y: buttonsStackView.frame.minY)
    
But, using AffineTranform does not affect any constraints then it would be very hard to manage as the constraints and the AffineTransform might be conflicted with each other. I tried it in my example project too and it didn't work well. I had constraints to change the location of the stackview according to the screen's orientation. Using the AffineTransform struct worked in portrait mode but when the screen rotated to landscape, some buttons went off the screen.

I think if it's a slide-in popup view like in this post, using AfflineTransform is okay because the popup view usually stay on top of other views and it does not need constraints relative to the other views so changing its location and size does not really affect the others.


How to detect device's orientation in Swift

There are two ways to detect a device's orientation:

1). The UIDevice.current.orientation property (instance of UIDeviceOrientation class:
- isFlat: when the device is held upward (toward the sky) or downward (toward the ground)
- isLandscape: when the device is held upright and the home button is on the right/left
- isPortrait: when the device is held upright and the home button is at the bottom/top

2). The UIApplication.shared.statusBarOrientation property:
- isLandscape
- isPortrait


Using Swift 3, the status bar is hidden by default in my app. However, the isLandscape and isPortrait still work correctly.

Which one should we use?
It depends on circumstances. In my case, I want to enable swipe gesture in portrait mode but disable it in landscape mode so UIApplication.shared.statusBarOrientation.isLandscape is the right one. If my device is firstly in landscape mode and then i put it on the table (face up), the swipe gesture should still be disable. The UIDevice.current.orientation.isLandscape property would return false and then the user would be able to swipe.




Monday, April 1, 2019

Swift: Dynamically Change A Label's Font Size Based On Device's Screen Size

Different devices have different screen sizes or resolutions, for example, iPhone SE has 640x1136 resolution (pixels) but iPhone 6 has 750x1334 resolution (pixels). We can use UIKit framework to obtain information about the screen resolutions.

Points are logical unit used in iOS. The number of pixels per point varies from devices. The more pixels per point, the clearer the icons and texts.


When developing an app to run on different devices, the text's size must be able to dynamically change or the text might look fine on one device but looks too big or too small on another.

Below is a custom label in which its font can change based on the device's screen size.
    
import Foundation
import UIKit

public class AdaptiveFontLabel: UILabel {
    private let iphone6HeightInPoints:CGFloat = 667
    
    var utfText:String?
    
    public required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        // On landscape mode, height is less than width
        let heightDiff = max(UIScreen.main.bounds.height, UIScreen.main.bounds.width) / iphone6HeightInPoints
        let newFontSize = font.pointSize * heightDiff
        
        font = UIFont(descriptor: font.fontDescriptor, size: newFontSize)
    }
    
    private func max(_ first:CGFloat, _ second:CGFloat) -> CGFloat {
        return first > second ? first : second
    }
}
    

The idea here is we need to test the label's font on a preferred device first to see it look ok. In my case, I chose iPhone 6, and the font size 21 looks perfect on it.

Then, I noted down the iPhone 6's screen size in points so that i can calculate the screen size difference (in points) between the iPhone 6 and the current device the app is running on. The font size is recalculated based on the screen difference.


The View's Margins in iOS

The top, leading, bottom, and trailing margins of a view define the spaces between the view's edges and its contents.



Setting layout margins in Interface Builder


The margins can be set in Interface Builder by updating the Layout Margins setting (in Size Inspector) to either Language Directional or Fixed then specify the values for Leading, Top, Bottom, and Trailing edges.


Then, we can create a constraint for the subview's edges relative to superview's margins as following:


Note that if we don't check the "Constraint to margins", it means we constraint the subview's edges relatively to its superview's edges, not the layout margins.



Setting layout margins programmatically


Open the ViewController.swift file and update the viewDidLoad() method as following:
    
import UIKit

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