Miscellaneous Flashcards

1
Q

What parameter of a UIView is used to turn on/off Auto Layout to dynamically calculate size and position???

A

translatesAutoresizingMaskIntoConstraints = false

AutoLayout translates the view’s autoresizing mask into a set of constraints that specify the view’s position. Only necessary if view is created in Interface Builder

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How to acquire the device dimensions?

A

UiScreen.main.bounds.width

UIScreen.main.bounds.height

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are the protocols that need to be adopted for UITableView?

A

UITableViewDataSource and UITableViewDelegate

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the purpose of UITableViewDataSource?

A

Populates the cells of the table. Manages the table’s data directly, or coordinates with other parts of your app to manage that data.

Returns section headers, cells for each row

Other responsibilities of the data source object include:
Reporting the number of sections and rows in the table.
Providing cells for each row of the table.
Providing titles for section headers and footers.
Configuring the table’s index, if any.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the purpose of the UITableViewDelegate?

A

Handles user interaction. Table interactions like swipes, row selection, heights for rows.

Key methods:

  • Create and manage custom header and footer views.
  • Specify custom heights for rows, headers, and footers.
  • Provide height estimates for better scrolling support.
  • Indent row content.
  • Respond to row selections.
  • Respond to swipes and other actions in table rows.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are some key functions of UITableViewDataSource?

A

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int

func numberOfSections(in tableView: UITableView) -> Int

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are some key functions of UITableViewDelegate?

A

func tableView(UITableView, didSelectRowAt: IndexPath)

func tableView(UITableView, heightForRowAt: IndexPath) -> CGFloat

func tableView(UITableView, didHighlightRowAt: IndexPath)

func tableView(UITableView, leadingSwipeActionsConfigurationForRowAt: IndexPath) -> UISwipeActionsConfiguration?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are the main calls to pull a file from the bundle?

A

Bundle.main.path(forResource:ofType)

if let filepath = Bundle.main.path(forResource: "example", ofType: "txt") {
    do {
        let contents = try String(contentsOfFile: filepath)
        print(contents)
    } catch {
        // contents could not be loaded
    }
} else {
    // example.txt not found!
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Code to read file into Data object?

A
let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let filePath1 = dir.appendingPathComponent("myfile")
// Turns into Data object
let dataBuffer = FileManager.default.contents(atPath:filePath1)

1) get the documentDIrectory user FileManager
2) get the file path by appending the filename to the document directory
3) Use FileManager or FileHandle to read.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the difference between FileManager and FileHandle?

A

FIleManager permits basic copying of entire files, opening files, moving files, etc. FileHandle permits advanced file handling: seeking to specific places in file, reading bytes, can be used with Devices and Network Sockets, etc.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is content hugging priority?

A

The larger the value, the more resistant a View is to being made larger than its intrinsic size.

So, larger the content hugging priority , the views bound will hug to the intrinsic content more tightly preventing the view to grow beyond its intrinsic content size.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is content compression resistance priority?

A

Higher priority the larger resistance is to shrinking.

If horizontal compression resistance priority is 750 and button width constraint priority is 1000, the button width takes precedence over resistance and a button with LONG name will still shrink.

If change horizontal resistance to 1000 and button width to 999, the resistance to shrinking takes priority over width and button width doesn’t shrink.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What are the five app states in the lifecycle?

A
not running
inactive
active
background
suspended.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What does info.plist do?

A

provides the system with information about the app’s configuration. (e.g., requires wifi, runs in background, respond to URLs, etc.)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What are the different UIEvent touch responder methods? (methods of UIResponder)

A

touchesBegan
touchesMoved
touchesEnded
touchesCancelled

touchesBegan(_ touches: Set, 
             with event: UIEvent?)
func touchesMoved(_ touches: Set, 
             with event: UIEvent?)
func touchesEnded(_ touches: Set, 
             with event: UIEvent?)
func touchesCancelled(_ touches: Set, 
                 with event: UIEvent?)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Describe how the responder chain works?

A

Every UIView or UIControl, any system object that deals with user interaction subclasses the UIResponder.

UIKit hit-tests to determine where touch event occurred, traverses the view hierarchy looking for the deepest subview that contains the specified touch, that becomes the FIRST RESPONDER.

First, the correct responder needs to be identified - the responder chain is travelled using the next responder method, from the initial UIView->SuperView->UIWindow->UIApplication->UIApplicationDelegate.

If a responder can handle the touch event, the responder chain is stopped and that responder “eats” or handles the touch event, unless it calls a super method of touch. If it cannot handle the touch event it’s passed to the next responder.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is Key-Value Observing?

A

Target-action mechanism that works between two objects. One object registers directly with another object and is notified when a value in it is changed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

How do you prevent a retain cycle when using closures? (what keywords are used?)

A

unowned or weak in a closure capture list

lazy var asHTML: () -> String = {
		        [unowned self, weak delegate] in
		        if let text = self.text {
		            return "\(text)\(self.name)>"
		        } else {
		            return ""
		        }
		  }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How do you code a Key-Value Observing between two objects MyClass1 and MyClass2 to observe a value?

A

Use dynamic and @objc on the value in MyClass1 to observe

class MyClass1{
  @objc dynamic var value:Bool = false
}
class MyClass2{
   var observation:NSKeyValueObservation?
  func registerObj(object:MyClass1){
      observation = observe(\.object.value, options:[.old,.new]){
          object, change in
      print("Old Value\(change.oldValue) New Value\(change.newValue)")
 }   }

}

var mc1:MyClass1 = MyClass1()
var mc2:MyClass2 = MyClass2()
mc2.register(object:mc1)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What’s the difference between unowned and weak keyword?

A

ARC does not increase the retain count of a weak object but ARC still monitors and tracks the weak instance; when retain count moves to 0 it makes the weak instance nil

Unowned means ARC does no memory management at all of the unowned object. Unowned is safe provided the object referred to will outlive the object that refers to it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is the danger when using unowned to reference to an object?

A

Unowned means ARC does no memory management; if the object referred to goes out of existence then you’ll have a dangling pointer

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Why should most delegates be referred to as weak?

A

Because the owner has a strong reference to the delegate and the delegate, set to self (owner), has a strong reference to the owner - you’ve created a retain cycle.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How are UserDefaults stored by the system?

A

Key-Value pairs stored in a .plist file.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What kind of data can you store in UserDefaults?

A

Standard types, Int, Double, String, Bool, Date, Array, Dictionary. Arbitrary data can be stored after its been encoded as a Data object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

Are CALayers part of the responder chain?

A

No, only UIViews and subclasses are participants in the responder chain.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What method is called when you’re embedding UIViewControllers before they’re completely instantiated? (containers)

A

prepare(for segue:sender:)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

If embedding multiple UIViewControllers how to setup and distinguish between them?(code)

A

In prepare(for segue:sender:), check the segue.identifier for the identifier (if assigned in Storyboard) or cast segue.destination to the type to check:

override func prepare(for segue:UIStoryboardSegue, sender:Any?){
if segue.identifier == “uppercontainer”{
upperVC = segue.destination as? UpperViewController
upperVC.delegate = self
}

}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Schedule a Timer

A

scaleTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { [unowned self] timer in

})

OR SEND USER DATA:

let context = ["key1":1, "key2":2]
        scaleTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(fireScaleTimer), userInfo: context, repeats: true)
 @objc func fireScaleTimer(timer:Timer){
        if let context = timer.userInfo as? [String:Int]{
             print(context["key1"])
        }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What types can stored properties belong to? What about computed properties?

A

Stored properties can belong to structs and classes but not to enums.

Computed properties can belong to structs, classes and enums.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

Create a custom accessor for a property named area:Double for a Square class that has a property length:Double

A

var area:Double {

get{
return length * length
}

set(newValue){ // calculate length off of the total area
length = sqrt(newValue)
}

}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

Substitute a custom type for Int named VolumeLevel

A

typealias VolumeLevel = Int

var volume:VolumeLevel = 0

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

Write the subscript code for a BankLine class that has an array “line” that holds People

A

subscript(index:Int)->People?{

   get{
        if index >=0 &amp;&amp; index < line.count{
            return line[index]
        }
       return nil
   }
  set(person){
    if index >=0 &amp;&amp; index < line.count{
        line[index] = person
    }
  }

}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

What object is at the top of the UIView Hierarchy?

A

UIWindow.

Applications have exactly one main window that is the ultimate superview of all other UIViews.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

What does the root ViewController link together?

A

The UIWindow and the interface the user in interacts.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

What are the steps to override touch UIResponder events in a ViewController on a specific UIView?

A

1) Identify the UIResponder touch method to override (touchesBegan, touchesMoved, touchesEnded, touchesCancelled)
2) Enabled user interaction on the view in question: myImageView.userInteractionEnabled = true
3) override the chosen UIResponder touch method

override func touchesBegan(touches: Set, withEvent event: UIEvent){

    super.touchesBegan(touches, withEvent: event)
        //4) Grab the first UITouch in the set
        let touch: UITouch = touches.first as! UITouch
        //5) Add code to test the UITouch view === imageVIew 
        if (touch.view == imageView){
            println("touchesBegan | This is an ImageView")
        }else{
            println("touchesBegan | This is not an ImageView")
        }

}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

What are the two objects that are passed to UIResponder methods like touchesBegan, touchesCancelled?

A

UITouch (Set) and UIEvent (Optional)

override func touchesMoved(touches: Set, withEvent event: UIEvent?){

}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

Describe what happens when a touch event occurs, how does the system react to the touch event?

A

When a touch event occurs, the system routes it to the appropriate responder and calls the appropriate method, such as touchesBegan(_:with:). The responder then uses the touches to determine an appropriate course of action.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

What call to make on UIEvent object to grab a finer grain list of UITouch objects?

A

event.coalescedTouches(for:)

Returns an array of all touches since the last event, including the last UITouch object actually delivered to the app.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

What method of UITouch can be used to get the CGPoint where the touch happens?

A

touch.preciseLocation(in: view:UIView?) -> CGPoint

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

Should the preciseLocation of a UITouch event be used to do hit testing?

A

No, hit testing against precise location may indicate touch is outside of the UIView that was touched.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

Describe the steps that happen during app launch?

A

1) UIApplicationMain function instantiates UIApplication and retains it for later use as UIApplication.shared
2) UIApplicationMain looks to see if storyboard is used, if so, UIApplicationMain instantiates UIWindow, sizes it, and retains it.
3) If storyboard, UIApplicationMain instantiates initial View Controller then assigns it as the window’s rootViewController property, retaining it.
4) UIApplicationMain calls the app delegate’s application(_:didFinishLaunchingWithOptions:)
5) UIApplicationMain sets the app’s key window calling makeKeyAndVisible.

UIApplicationMain->UIWindow->RootViewController->application(_:didFInishLaunchingWithOptions)->makeKeyAndVisible

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

What happens when a ViewController becomes the rootViewController during launch?

A

Its main view is made the one and only immediate subview of the main UIWindow.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

What are the high-level steps to manually launch an app?

A

In Application(:didFinishLaunchingWithOptions):

1) Instantiate UIWindow
2) Instantiate initial ViewController, configure it, assign it as the Window’s rootViewController
3) call makeKeyAndVisible on the window

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

What two view related properties does UIView possess?

A

superview and subviews (array of UIViews ordered back to front)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

What methods to call to add and subtract UIViews from a hierarchy?

A

addSubview(_:) adds another UIView to the caller’s subviews.

removeFromSuperview(): removes the caller from its superview hierarchy

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

When you call addSubview(_:) where is the added UIView placed in the hierarchy?

A

It’s added to the end of the superview’s subviews, thus it’s drawn last.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

What method calls can be used to place subviews at different locations in the superview’s hierarchy?

A
insertSubview(_:at:)
insertSubview(_:belowSubview)
insertSubview(_:aboveSubview)
exchangeSubview(at:withSubviewAt:)
bringSubviewToFront(_:)
sendSubviewToBack(_:)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

Difference between frame and bounds?

A

A view’s frame property is the CGRect representation of its position in the superview’s coordinate system. Bounds is the CGRect representation in its own coordinates.

(Remember 0,0 is top left of screen for frame or top left of view for bounds.)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

Which app delegate methods are called when: app launches from scratch?

A

application(_: didFinishLaunchingWithOptions)

applicationDidBecomeActive(_:)

50
Q

Which app delegate methods are called when: user clicks home button when app is foreground?

A

applicationWillResignActive(_:)

applicationDidEnterBackground(_:)

51
Q

Which app delegate methods are called when: user summons background app to front?

A

applicationWillEnterForeground(_:)

applicationDidBecomeActive(_:)

52
Q

Which app delegate methods are called when: screen is locked?

A

applicationWillResignActive(_:)

applicationDidEnterBackground(_:)

53
Q

Which app delegate methods are called when:screen unlocked (and your app was originally in foreground)?

A

applicationWIllEnterForeground(_:)

applicationDidBecomeActive(_:)

54
Q

Which app delegate methods are called when:user double clicks home then choses a different app? Chooses your app?

A

Chooses different app:
applicationWillResignActive(:)
applicationDidEnterBackground(
:)

Chooses your app:
applicationWillResignActive(:)
applicationDidBecomeActive(
:)

55
Q

Which app delegate methods are called when:user double clicks home then shuts down your app?

A

applicationWillResignActive(_:)

applicationWIllTerminate(_:)

56
Q

True/False: Changing a UIView frame size changes its bounds size? What about the converse, does bounds change frame?

A

True & true

57
Q

True/False: Changing a UIView’s bounds changes its center?

A

False. Bounds and center are independent.

58
Q

If you have two UIViews, v2 a subView of v1, and want to make their centers equal, is the following statement correct? v2.center = v1.center?

A

No, not correct. The two centers are in different coordinate systems and will have unpredictable results.

59
Q

If UIView V2 is a subview of UIView V1, how do you set the center of V2 to that of V1?

A

v2.center = v2.convert(v2.center, to:v1)

OR

v2.center = CGPoint(v1.bounds.midx, v1.bounds.midY)

60
Q

Rotate a UIView 45% then scale it?

A

let v1 = UIView.init(frame:CGRect.init(x:0,y:0, width:50,height:100))

v1. transform = CGAffineTransform(rotationAngle: 45 * .pi/180)
v1. transform = CGAffineTransform(scaleX:1.8, y:1.2)

61
Q

How to determine landscape/device type using UITraitCollection?

A

horizontalSizeClass and verticalSizeClass can be either .regular or .compact

  • Both are .regular: iPad
  • Horizontal is .compact and vertical is .regular: iPhone w/app in portrait
  • Horizontal is .regular and vertical is compact: big iPhone in landscape
  • horizontal and vertical are .compact: app in landscape on iPhone
62
Q

How would you manually layout subviews?

A

Override the layoutSubviews method then manually position all subviews of the UIView.

63
Q

How do you activate a set of constraints all at once?

A

NSLayoutConstraint.activate([
v2.leadingAnchor.constraint(equalTo:v1.leadingAnchor),
v2.topAnchor.constraint(equalTo:v1.topAnchor)
])

64
Q

What method is called when a device switches from portrait->landscape or landscape->portrait?

A

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) lets you modify constraints as well as add a coordinator that can perform animations

Alternatively, traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) can be used to inspect if a change was made from portrait to landscape and customize interface. (make sure to call super)

  • (void) traitCollectionDidChange: (UITraitCollection *) previousTraitCollection {
    [super traitCollectionDidChange: previousTraitCollection];
    if ((self.traitCollection.verticalSizeClass != previousTraitCollection.verticalSizeClass)
    || (self.traitCollection.horizontalSizeClass != previousTraitCollection.horizontalSizeClass)) {
    // your custom implementation here
    }
    }
65
Q

How to connect UIView, properties, etc to InterfaceBuilder from code?

A

Make class @IBDesignable and properties @IBInspectable

66
Q

What method is called when the app layout takes place?

A

layoutSubviews: - trigger with a call to layoutIfNeeded or setNeedsLayout.

67
Q

Name a few ways of passing information back and forth between classes and instances?

A

Key-Value Observing
Delegation
Notifications

68
Q

What are two methods that can be used to instantiate a UIImage object from a file in the asset catalog? What are the differences between them?

A

let img = UIImage.init(named:”mypic”) //uses caching

if let path = Bundle.main.path(forResource:"mypic", ofType:"png"){
    let im2 = UIImage.init(contentsOfFile:path) // no caching
}
69
Q

What class are HTTP requests made through?

A

URLSession

70
Q

What method to call to start a URLSession?

A

get a task from the URLSession object and call resume() on task. Resume() initially starts and re-starts a task.

let task = session.downloadTask(with:url){}
task.resume()
71
Q

How do you grab and then write to the main UI thread?

A
DispatchQueue.main.async{
// update UI
}
72
Q

What are the high-level steps/Classes required to download a file?

A

1) Create URL to file
2) Grab a URLSession
3) Create a download task from the URLSession
4) make the completion task callback
4) resume() the task

let s = "https://url"
let url = URL(string:s)!
let session = URLSession.shared
let task = session.downloadTask(with:url){fileURL, resp, err in
	if let url = fileURL, let d = try? Data(contentsOf:url){
		let im = UIImage(data:d)
		DispatchQueue.main.async{
			self.iv.image = im
		}
	}
}

task.resume()

73
Q

How to avoid a retain cycle when using URLSessions with Delegate as UIViewController

A

call finishTasksAndInvalidate or invalidateAndCancel from viewWillDisappear().

URLSession retains its delegate which is “self” or the UIViewController. The UIViewController

74
Q

Describe the app lifecycle from startup?

A

1) UIKit provides Core App Objects , runs the app main event loop and displays content on-screen
2) UIApplicationMain creates UIApplication and AppDelegate
3) UIApplicationMain instantiates UIWindow and assigns the window to the AppDelegate’s window property (ensuring its retained for the lifetime of the app)
4) UIApplicationMain looks for storyboard and instantiates the initial ViewController making it the rootViewController
5) UIApplicationMain calls application:didFinishLaunchingWithOptions
6) UIApplicationMain calls makeKeyAndVisible
7) app becomes activated
8) applicationDidBecomeActive: is called

9 Event Loop runs

75
Q

Describe the app lifecycle after launch is complete?

A

viewDidLoad(): called once for instantiation of VC
viewWillAppear()->viewDidAppear()
viewWillDisappear()->viewDidDisappear()

If app is not terminated and user comes back to select it
viewWillAppear() is called otherwise viewDidLoad()

76
Q

Manually instantiate an app

A

From didFinishLaunchingWithOptions:

1) Instantiate the entry point VC
2) set the window
3) set the window RootVC
4) call makeKeyAndVisible

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool
    {
		//INSTANTIATE THE ENTRY POINT VC
        let mainViewController = MainViewController()
        mainViewController.title = "Main"
		//SET THE WINDOW 
        let frame = UIScreen.main.bounds
        window = UIWindow(frame: frame)
		//SET THE WINDOW ROOT VIEW CONTROLLER
        window!.rootViewController = mainViewController
        window!.makeKeyAndVisible()
    return true
} }
77
Q

What two methods are called from the root UIViewController after app instantiated (and any other newly created VCs) as well as when device is rotated to setup the UIViews?

A

viewWillLayoutSubviews and viewDidLayoutSubviews

willLayout: called right before layoutSubviews
didLayout: called right after layoutSubviews

78
Q

Name some UIView lifecycle methods?

A
didAddSubview(_:)
willRemoveSubview(_:)
willMove(toSuperView:)
didMoveToSuperview
willMove(toWindow:)
didMoveToWindow
79
Q

How would you interject your code in the startup process to, say, return an app to its state when it was closed?

A

The app isn’t visible, makeKeyAndVisible isn’t called, until didFinishLaunchingWithOptions completes. Inject code here to setup application state prior to user seeing the rootVC.

80
Q

When does applicationDidBecomeActive(_ application:) get called?

A

Transition from inactive to active

81
Q

When does applicationWillResignActive(_ application:) get called?

A

Transition from active too Inactive.

82
Q

How might you make adjustments or run additional code after a user hits the Home Screen button?

A

Sequence of calls is applicationWillResignActive -> applicationDidEnterBackground when user hits home.

So, you can execute code in either, choose Background. You get 5 seconds to execute code, after that app is terminated and purged from memory.

Call beginBackgroundTask(expirationHandler:) to request additional time.

83
Q

Name some important HTTP Codes

A

200 OK (request succeeded)

301 Moved Permanently (new URI in response)
302 Found (temp URI change)

400 Bad Request (invalid syntax)
401 Unauthorized (unauthenticated)
403 Forbidden (bad access rights)
404 Not Found

500 Server Error
502 Bad Gateway (invalid response from gateway)
503 Service Unavailable (server unready to handle request)

84
Q

What are the main calls when using Keyframe Animations?

A

1) Create the initial call to animateKeyframes:
UIView.animateKeyframes(withDuration:1.0, delay:0.0, options:[], animations:{// add keyframes here})

2) Add individual keyframes with relativeStartTime, relativeDuration, and animations
UIView.addKeyframe(withRelativeStartTime: 0.0,
relativeDuration: 0.25, animations: {
self.button.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
})
UIView.addKeyframe(withRelativeStartTime: 0.25,
relativeDuration: 0.25, animations: {
self.button.transform = CGAffineTransform(scaleX: 0.1, y: 0.1)
})

3) Decide if you want a completed block

}){completed in
  // write code to complete

}

85
Q

What kind of qualities of UIViews can keyframe animations operate on?

A

UIView properties (bounds, frame, center, backgroundColor, alpha…

86
Q

What kind of qualities of UIView can UIViewPropertyAnimator work on?

A

UIView properties: Operates on bounds, frame, center, alpha, backgroundColor, transform properties. Pause, stop, reverse, alter the speed of animations. Not layer properties (like cornerRadius or shadowOpacity)

87
Q

What are the different options to animate UIViews?

A

Keyframe Animations
UIViewPropertyAnimator
CABasicAnimation
CALayer Animations

88
Q

Is frame animatable at the CALayer level? UIView?

A

False. False.

89
Q

What are the main calls when using a UIViewPropertyAnimator?

A

1) Create the animator object and assign the animation:

let animator = UIViewPropertyAnimator(duration: duration, curve: .linear) {
    self.redSquare.backgroundColor = .green
}

2) add additional animations:
animator.addAnimations {
self.redSquare.layer.cornerRadius = 50.0
}

3) add completion;
animator.addCompletion { position in
if position == .end {
print(“Second completion”)
}
}

4) start animation
animator. startAnimation()

90
Q

Why use UIViewPropertyAnimator to animate a UIView?

A

With UIViewPropertyAnimator you can add custom Timing curve to the timingParameters. As well, you can interact with the animation manually using the UIViewPropertyAnimator fractionComplete property.

// Custom timing
let cubicTIming = UICubicTimingParameters(controlPoint1:point1, controlPoint2:point2)
let animator = UIViewPropertyAnimator(duration: duration, timingParameters: cubicTiming)) {
    self.view.layoutIfNeeded()
}
// Fraction complete (connect a slider and adjust the animation
// based on slider value
@objc func sliderChanged(_ sender: UISlider){ 
	animator.fractionComplete = CGFloat(sender.value)
}
91
Q

Why use KeyFrame Animations?

A

To have the ability to fine tune the start times and interleave different animations.

92
Q

Why use CABasicAnimation?

A

So you can animate CALayer properties. Others cannot like Keyframe, UIViewPropertyAnimator

93
Q

Change the value of cornerRadius using animation.

A
1) Use CABasicAnimation, with the keyPath of the CALayer property to animate:
let cornerAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.cornerRadius))

2) Set the from/to values and duration:
cornerAnimation.fromValue = oldValue
cornerAnimation.toValue = newValue
cornerAnimation.duration = 1.0

3) Set the final value of the CALayer to the new value:
styledButton.layer.cornerRadius = newValue

4) Add the animation to the layer - it triggers immediately
styledButton.layer.add(cornerAnimation, forKey:#keyPath(CALayer.cornerRadius))

94
Q

Why use CATransaction?

A

Interleave standard view property animations amongst layer property animations and fine-tune exact timings to smooth and sync them inside a single CATransaction block

Granular coordination of multi-step animations.

95
Q

Is a UIView a UIResponder?

A

True

96
Q

How do UITouches arrive at UIResponders?

A

Wrapped up inside a UIEvent.

97
Q

When adding a child/embedded VC what’s the call?

A

addChildViewController(child)

98
Q

How would you remove a child VC from a parentVC?

A

call the removeFromParentViewController() method

99
Q

Do structs have a concept of inheritance?

A

False, Structs can implement protocols but cannot inherit.

100
Q

What are optionals for?

A

Test if an object has a value or is empty. Test changing conditions over time and prevent crashes - you’re writing code to anticipate the value in a variable and do something to react to a non-value - proactive code that prevents crashes.

101
Q

If you want to add a user-defined class/instance to a set what must it conform to in order to be added?

A

Hashable. So long as the element is hashable then equality can be tested.

102
Q

Can you add a tuple of Ints to a Set?

A

No, Tuples can’t be members of a set unless its a custom type that conforms to Hashable. For ex, the following type can be added to a set and used to check if exists in set, etc:

struct MyPoint:Hashable{
var x:Int
var y:Int
}

As long as each of the properties of the class/structure conform to Hashable themselves Swift will generate the hash(into:) method.

103
Q

What method do you override if you want to create your own hash method for a custom class/struct you’ve created?

A

hash(into:Hasher) - this method is auto generated by Swift if properties in the class/struct already conform to Hashable but if you want to write your own custom hash function, add the hash(into:Hasher) method to your type:

struct iPad: Hashable {
var serialNumber: String
var capacity: Int

    //only use serial number to hash
    func hash(into hasher: inout Hasher) {
        hasher.combine(serialNumber)
    }
}

// If you then wanted to add the other property, capacity, call combine again (call it repeatedly in a specific order will affect the output hash)

104
Q

What are some differences between using UIView animations and UIViewPropertyAnimator?

A

UIViewPropertyAnimator can do everything that UIView does and more:

  • It can have multiple completion blocks (addCompletion())
  • Can configure it in multiple steps/commands before calling startAnimation (UIView animations are one block)
  • Can add multiple animations with addAnimations
  • Can do custom timing curves using the timingParameters parameter with a UICubicTimingParameters or other Bezier Curve vs the standards .curveEaseInOut, .curveEaseIn, .curveEaseOut, etc.
  • If you might need to cancel the animation, the PropertyAnimator has the option to pauseAnimation() and continueAnimation…which you might want to do in the event
105
Q

Can you autoreverse a standard UIView animation?

A

Yes, use the UIView.AnimationOptions (options: parameter) by setting it and calling it in animate:

let opts = UIView.AnimationOptions = .autoreverse

UIView.animate(withDuration:1, delay:0, options:opts, animations:{
self.v.center.x += 100
}, completion:nil)

106
Q

What are the two spring-based animation properties of UIView.animate? How are they defined?

A

usingSpringWithDamoing, initialSpringVelocity

Damping Ratio: describes the amount of final oscillation. 0.0-1.0, where 1.0 settles directly into place and 0.0 waggles around

Initial Velocity: higher value cause greater overshoot depending on Damping Ratio. The higher the value the more the overshoot

107
Q

How would you stop an animation and make it finish much faster, say if a user cancelled something?

A

Use UIViewPropertyAnimator, pauseAnimation() and contnueAnimation():

let anim = UIViewPropertyAnimator(duration 4, timingParameters: UICubicTimingParameters())
self.addAnimations{
   self.v.center.x += 100
}

self.startAnimation()

self. anim.pauseAnimation()
self. anim.continueAnimation(withTimingParameters:nil, durationFactor:0.1)

108
Q

What would you use to animate a multi-stage animation, a complex animation that requires a sequence of events to occur?

A

Keyframe Animations: with the animateKeyframes UIView method, placing each keyframe at a specific start time and duration, and sequencing each with the addKeyframe method.

UIView.animateKeyframes(withDuration: 1.0,
delay: 0.0, options: [], animations: {

  UIView.addKeyframe(withRelativeStartTime: 0.0, 
  relativeDuration: 0.25, animations: {
      self.button.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
   })
109
Q

Is UIView simply a wrapper of CALayer?

A

True

110
Q

When you want to animate layer properties which animation should you use?

A

CABasicAnimation

111
Q

Using CABasicAnimation, animate the position of a UIView named myView to the right 50 pixels and down 50 px.

A

let myAnimation = CABasicAnimation(keyPath: “position”)
myAnimation.fromValue = [50, 100]
myAnimation.toValue = [100, 150]
myAnimation.duration = 2.0
myAnimation.timingFunction = CAMediaTimingFunction(name:CAMediaTimingFunctionName.easeIn)

//Adding makes it trigger
myView.layer.add(myAnimation, forKey:#keyPath(CALayer.position)
112
Q

What’s the difference between viewDidLoad() and loadView()

A

loadView() is called before the ViewController views are loaded where viewDidLoad is called after the views are created for final tweaking before viewWillAppear/viewDidAppear

113
Q

Programmatically create a UITabBarController

A

1) Delete main storyboard
2) Create new UITabBarController class file (subclass of UITabBarController)
3) Create tab VCs in viewDidLoad() and add them as UITabBarItems

let firstViewController = firstVC()      
firstViewController.tabBarItem = UITabBarItem(tabBarSystemItem: .search, tag: 0)
let secondViewController = secondVC()
secondViewController.tabBarItem = UITabBarItem(tabBarSystemItem: .more, tag: 1)
let tabBarList = [firstViewController, secondViewController]
viewControllers = tabBarList

4) Update AppDelegate didFinishLaunchingWithOptions application method:

window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = UINavigationController(rootViewController: YourTabBarController())
window?.makeKeyAndVisible()

114
Q

When using a UICollectionView what should you use to reference a cell in the collection from the indexPath?

A

item or row are the same. in the context of UITTableView use row but UICollectionView use item - row doesn’t make sense in the CollectionView because “rows” are determined by the flow layout returning the size of a cell.

115
Q

What are the delegates you need to implement for a UICollectionView?

A

UICollectionViewDelegateFlowLayout

UICollectionViewDataSource

UICollectionViewDelegate

(UIScrollViewDelegate is optional)

116
Q

How do you set an action for a UIButton (or any UIControl) programmatically to react to a tap on the button?

A

Use addTarget method for any UIControl to add touch gesture:
button.addTarget(self, action: #selector(showDropDownCategories(_:)), for: UIControl.Event.touchUpInside)

You could also place a TapGestureRecognizer on the button (UITapGestureRecognizer.init(target:self, action:#selector(target(_:))

117
Q

What method is called to remove touch handling on a UIControl?

A

removeTarget(_ target: Any?, action: Selector?, for controlEvents: UIControl.Event)

where control events are from the set touchUpInside

118
Q

Name some UIControls

A

UIButton, UIDatePicker, UISlider, UISegmentedControl, UIPageControl, UISlider, UIStepper, UISwitch

119
Q

Name some UIControl.Events (used when doing Target-Actions using addTarget(_:action:for))

A

touchDown
touchDownRepeat

touchDragInside
touchDragOutside

touchUpInside
touchUpOutside

touchCancel

editingDidBegin
editingDidEnd

allEvents

120
Q

What are high-level summaries for HTTP code ranges?

A
  • 1xx: Informational and only defined under HTTP 1.1.
  • 2xx: The request went OK, here’s your content.
  • 3xx: The resource was moved somehow to somewhere.
  • 4xx: The source of the request did something wrong.
  • 5xx: The server crashed due to some error on its code.
121
Q

Name some HTTP Codes and what they do

A
200 OK: request fine content returned
201 CREATED:  the resource was created
301 MOVED PERM: redirect
400 BAD REQUEST: malformed request, should return error for developer
401 UNAUTHORIZED: Auth issue
403 FORBIDDEN: not auth issue, just inaccessible
404 NOT FOUND
500 SERVER ERROR