Miscellaneous Flashcards

(121 cards)

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
Are CALayers part of the responder chain?
No, only UIViews and subclasses are participants in the responder chain.
26
What method is called when you're embedding UIViewControllers before they're completely instantiated? (containers)
prepare(for segue:sender:)
27
If embedding multiple UIViewControllers how to setup and distinguish between them?(code)
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 } }
28
Schedule a Timer
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"]) } ``` }
29
What types can stored properties belong to? What about computed properties?
Stored properties can belong to structs and classes but not to enums. Computed properties can belong to structs, classes and enums.
30
Create a custom accessor for a property named area:Double for a Square class that has a property length:Double
var area:Double { get{ return length * length } set(newValue){ // calculate length off of the total area length = sqrt(newValue) } }
31
Substitute a custom type for Int named VolumeLevel
typealias VolumeLevel = Int | var volume:VolumeLevel = 0
32
Write the subscript code for a BankLine class that has an array "line" that holds People
subscript(index:Int)->People?{ ``` get{ if index >=0 && index < line.count{ return line[index] } return nil } ``` ``` set(person){ if index >=0 && index < line.count{ line[index] = person } } ``` }
33
What object is at the top of the UIView Hierarchy?
UIWindow. Applications have exactly one main window that is the ultimate superview of all other UIViews.
34
What does the root ViewController link together?
The UIWindow and the interface the user in interacts.
35
What are the steps to override touch UIResponder events in a ViewController on a specific UIView?
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") } ``` }
36
What are the two objects that are passed to UIResponder methods like touchesBegan, touchesCancelled?
UITouch (Set) and UIEvent (Optional) override func touchesMoved(touches: Set, withEvent event: UIEvent?){ }
37
Describe what happens when a touch event occurs, how does the system react to the touch event?
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.
38
What call to make on UIEvent object to grab a finer grain list of UITouch objects?
event.coalescedTouches(for:) Returns an array of all touches since the last event, including the last UITouch object actually delivered to the app.
39
What method of UITouch can be used to get the CGPoint where the touch happens?
touch.preciseLocation(in: view:UIView?) -> CGPoint
40
Should the preciseLocation of a UITouch event be used to do hit testing?
No, hit testing against precise location may indicate touch is outside of the UIView that was touched.
41
Describe the steps that happen during app launch?
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
42
What happens when a ViewController becomes the rootViewController during launch?
Its main view is made the one and only immediate subview of the main UIWindow.
43
What are the high-level steps to manually launch an app?
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
44
What two view related properties does UIView possess?
superview and subviews (array of UIViews ordered back to front)
45
What methods to call to add and subtract UIViews from a hierarchy?
addSubview(_:) adds another UIView to the caller's subviews. | removeFromSuperview(): removes the caller from its superview hierarchy
46
When you call addSubview(_:) where is the added UIView placed in the hierarchy?
It's added to the end of the superview's subviews, thus it's drawn last.
47
What method calls can be used to place subviews at different locations in the superview's hierarchy?
``` insertSubview(_:at:) insertSubview(_:belowSubview) insertSubview(_:aboveSubview) exchangeSubview(at:withSubviewAt:) bringSubviewToFront(_:) sendSubviewToBack(_:) ```
48
Difference between frame and bounds?
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.)
49
Which app delegate methods are called when: app launches from scratch?
application(_: didFinishLaunchingWithOptions) | applicationDidBecomeActive(_:)
50
Which app delegate methods are called when: user clicks home button when app is foreground?
applicationWillResignActive(_:) | applicationDidEnterBackground(_:)
51
Which app delegate methods are called when: user summons background app to front?
applicationWillEnterForeground(_:) | applicationDidBecomeActive(_:)
52
Which app delegate methods are called when: screen is locked?
applicationWillResignActive(_:) | applicationDidEnterBackground(_:)
53
Which app delegate methods are called when:screen unlocked (and your app was originally in foreground)?
applicationWIllEnterForeground(_:) | applicationDidBecomeActive(_:)
54
Which app delegate methods are called when:user double clicks home then choses a different app? Chooses your app?
Chooses different app: applicationWillResignActive(_:) applicationDidEnterBackground(_:) Chooses your app: applicationWillResignActive(_:) applicationDidBecomeActive(_:)
55
Which app delegate methods are called when:user double clicks home then shuts down your app?
applicationWillResignActive(_:) | applicationWIllTerminate(_:)
56
True/False: Changing a UIView frame size changes its bounds size? What about the converse, does bounds change frame?
True & true
57
True/False: Changing a UIView's bounds changes its center?
False. Bounds and center are independent.
58
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?
No, not correct. The two centers are in different coordinate systems and will have unpredictable results.
59
If UIView V2 is a subview of UIView V1, how do you set the center of V2 to that of V1?
v2.center = v2.convert(v2.center, to:v1) OR v2.center = CGPoint(v1.bounds.midx, v1.bounds.midY)
60
Rotate a UIView 45% then scale it?
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
How to determine landscape/device type using UITraitCollection?
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
How would you manually layout subviews?
Override the layoutSubviews method then manually position all subviews of the UIView.
63
How do you activate a set of constraints all at once?
NSLayoutConstraint.activate([ v2.leadingAnchor.constraint(equalTo:v1.leadingAnchor), v2.topAnchor.constraint(equalTo:v1.topAnchor) ])
64
What method is called when a device switches from portrait->landscape or landscape->portrait?
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
How to connect UIView, properties, etc to InterfaceBuilder from code?
Make class @IBDesignable and properties @IBInspectable
66
What method is called when the app layout takes place?
layoutSubviews: - trigger with a call to layoutIfNeeded or setNeedsLayout.
67
Name a few ways of passing information back and forth between classes and instances?
Key-Value Observing Delegation Notifications
68
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?
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
What class are HTTP requests made through?
URLSession
70
What method to call to start a URLSession?
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
How do you grab and then write to the main UI thread?
``` DispatchQueue.main.async{ // update UI } ```
72
What are the high-level steps/Classes required to download a file?
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
How to avoid a retain cycle when using URLSessions with Delegate as UIViewController
call finishTasksAndInvalidate or invalidateAndCancel from viewWillDisappear(). URLSession retains its delegate which is "self" or the UIViewController. The UIViewController
74
Describe the app lifecycle from startup?
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
Describe the app lifecycle after launch is complete?
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
Manually instantiate an app
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
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?
viewWillLayoutSubviews and viewDidLayoutSubviews willLayout: called right before layoutSubviews didLayout: called right after layoutSubviews
78
Name some UIView lifecycle methods?
``` didAddSubview(_:) willRemoveSubview(_:) willMove(toSuperView:) didMoveToSuperview willMove(toWindow:) didMoveToWindow ```
79
How would you interject your code in the startup process to, say, return an app to its state when it was closed?
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
When does applicationDidBecomeActive(_ application:) get called?
Transition from inactive to active
81
When does applicationWillResignActive(_ application:) get called?
Transition from active too Inactive.
82
How might you make adjustments or run additional code after a user hits the Home Screen button?
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
Name some important HTTP Codes
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
What are the main calls when using Keyframe Animations?
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
What kind of qualities of UIViews can keyframe animations operate on?
UIView properties (bounds, frame, center, backgroundColor, alpha...
86
What kind of qualities of UIView can UIViewPropertyAnimator work on?
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
What are the different options to animate UIViews?
Keyframe Animations UIViewPropertyAnimator CABasicAnimation CALayer Animations
88
Is frame animatable at the CALayer level? UIView?
False. False.
89
What are the main calls when using a UIViewPropertyAnimator?
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
Why use UIViewPropertyAnimator to animate a UIView?
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
Why use KeyFrame Animations?
To have the ability to fine tune the start times and interleave different animations.
92
Why use CABasicAnimation?
So you can animate CALayer properties. Others cannot like Keyframe, UIViewPropertyAnimator
93
Change the value of cornerRadius using animation.
``` 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
Why use CATransaction?
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
Is a UIView a UIResponder?
True
96
How do UITouches arrive at UIResponders?
Wrapped up inside a UIEvent.
97
When adding a child/embedded VC what's the call?
addChildViewController(child)
98
How would you remove a child VC from a parentVC?
call the removeFromParentViewController() method
99
Do structs have a concept of inheritance?
False, Structs can implement protocols but cannot inherit.
100
What are optionals for?
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
If you want to add a user-defined class/instance to a set what must it conform to in order to be added?
Hashable. So long as the element is hashable then equality can be tested.
102
Can you add a tuple of Ints to a Set?
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
What method do you override if you want to create your own hash method for a custom class/struct you've created?
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
What are some differences between using UIView animations and UIViewPropertyAnimator?
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
Can you autoreverse a standard UIView animation?
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
What are the two spring-based animation properties of UIView.animate? How are they defined?
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
How would you stop an animation and make it finish much faster, say if a user cancelled something?
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
What would you use to animate a multi-stage animation, a complex animation that requires a sequence of events to occur?
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
Is UIView simply a wrapper of CALayer?
True
110
When you want to animate layer properties which animation should you use?
CABasicAnimation
111
Using CABasicAnimation, animate the position of a UIView named myView to the right 50 pixels and down 50 px.
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
What's the difference between viewDidLoad() and loadView()
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
Programmatically create a UITabBarController
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
When using a UICollectionView what should you use to reference a cell in the collection from the indexPath?
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
What are the delegates you need to implement for a UICollectionView?
UICollectionViewDelegateFlowLayout UICollectionViewDataSource UICollectionViewDelegate (UIScrollViewDelegate is optional)
116
How do you set an action for a UIButton (or any UIControl) programmatically to react to a tap on the button?
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
What method is called to remove touch handling on a UIControl?
removeTarget(_ target: Any?, action: Selector?, for controlEvents: UIControl.Event) where control events are from the set touchUpInside
118
Name some UIControls
UIButton, UIDatePicker, UISlider, UISegmentedControl, UIPageControl, UISlider, UIStepper, UISwitch
119
Name some UIControl.Events (used when doing Target-Actions using addTarget(_:action:for))
touchDown touchDownRepeat touchDragInside touchDragOutside touchUpInside touchUpOutside touchCancel editingDidBegin editingDidEnd allEvents
120
What are high-level summaries for HTTP code ranges?
* 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
Name some HTTP Codes and what they do
``` 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 ```