Miscellaneous Flashcards
What parameter of a UIView is used to turn on/off Auto Layout to dynamically calculate size and position???
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 to acquire the device dimensions?
UiScreen.main.bounds.width
UIScreen.main.bounds.height
What are the protocols that need to be adopted for UITableView?
UITableViewDataSource and UITableViewDelegate
What is the purpose of UITableViewDataSource?
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.
What is the purpose of the UITableViewDelegate?
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.
What are some key functions of UITableViewDataSource?
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
func numberOfSections(in tableView: UITableView) -> Int
What are some key functions of UITableViewDelegate?
func tableView(UITableView, didSelectRowAt: IndexPath)
func tableView(UITableView, heightForRowAt: IndexPath) -> CGFloat
func tableView(UITableView, didHighlightRowAt: IndexPath)
func tableView(UITableView, leadingSwipeActionsConfigurationForRowAt: IndexPath) -> UISwipeActionsConfiguration?
What are the main calls to pull a file from the bundle?
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! }
Code to read file into Data object?
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.
What is the difference between FileManager and FileHandle?
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.
What is content hugging priority?
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.
What is content compression resistance priority?
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.
What are the five app states in the lifecycle?
not running inactive active background suspended.
What does info.plist do?
provides the system with information about the app’s configuration. (e.g., requires wifi, runs in background, respond to URLs, etc.)
What are the different UIEvent touch responder methods? (methods of UIResponder)
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?)
Describe how the responder chain works?
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.
What is Key-Value Observing?
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 do you prevent a retain cycle when using closures? (what keywords are used?)
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 do you code a Key-Value Observing between two objects MyClass1 and MyClass2 to observe a value?
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)
What’s the difference between unowned and weak keyword?
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.
What is the danger when using unowned to reference to an object?
Unowned means ARC does no memory management; if the object referred to goes out of existence then you’ll have a dangling pointer
Why should most delegates be referred to as weak?
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 are UserDefaults stored by the system?
Key-Value pairs stored in a .plist file.
What kind of data can you store in UserDefaults?
Standard types, Int, Double, String, Bool, Date, Array, Dictionary. Arbitrary data can be stored after its been encoded as a Data object.
Are CALayers part of the responder chain?
No, only UIViews and subclasses are participants in the responder chain.
What method is called when you’re embedding UIViewControllers before they’re completely instantiated? (containers)
prepare(for segue:sender:)
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
}
}
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"]) }
}
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.
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)
}
}
Substitute a custom type for Int named VolumeLevel
typealias VolumeLevel = Int
var volume:VolumeLevel = 0
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 } }
}
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.
What does the root ViewController link together?
The UIWindow and the interface the user in interacts.
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") }
}
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?){
}
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.
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.
What method of UITouch can be used to get the CGPoint where the touch happens?
touch.preciseLocation(in: view:UIView?) -> CGPoint
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.
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
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.
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
What two view related properties does UIView possess?
superview and subviews (array of UIViews ordered back to front)
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
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.
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(_:)
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.)