CS193P Notes PDF

Title CS193P Notes
Course Iphone And Ipad Application Programming
Institution Stanford University
Pages 17
File Size 231.3 KB
File Type PDF
Total Downloads 98
Total Views 133

Summary

Notes I took as a student in Paul Hegarty's class at Stanford University, CS193P: iOS Programming....


Description

Lecture 1 4/1/19: - We’ll always do single view app - Team - your name, org - your name, org id - edu.stanford.cs193p.rcole34 - Cool testing functionality but no time to teach it lol - Save projects to Developer folder in home directory - Checking git repo source control lets you set checkpoints even if working alone - Navigator is gray thing on the left side - Inspector is right side stuff - Then primary editor - duh - Can make console pop up from bottom too - Main.storyboard creates your UI - Get UI items from library - build responsively not staticly - ViewController.swift is code to control UI - Import foundation to get arrays and all that fun non-UI stuff - UIKit import gets all your UI things - Swift is single-inheritance big time OOP deal - To add event handlers - Hold control and drag from button into code - CHANGE TYPE FROM ANY TO UIBUTTON - Can give variables multiple names (external then internal) - Underscore for name means we don’t have to specify that variable name - All instance variables must be initialized, either by giving it a value or having an init class - Don’t touch internal XML of UI Lecture 2 4/3/19: - “nil” is special value only for an Optional that does not have a value - To make a new file (like for a model) go to File > New > File - Select swift file usually, or Cocoa Touch Class for extending something - Make struct to represent basic fundamental part of game - Structs have no inheritance - Structs are value types, classes are reference types - Reference types live in heap and references are pointers to that one shared thing in the heap - Value types are on the stack and are copied in their entirety when we make a new one or assign something to it - Struct has default init to initialize all params - Can make your own initializer in struct - Then you lose your other default constructor - Put gameplay logic in model classes - If you need something to wait until everything else is initialized, make it a “lazy var” won’t get initialized until we ask for it

Lecture 3 4/8/19: - Drag stuff around and line up with blue lines for system to know what you want it to line up with - Can select things and click embed in view at bottom and then select stack view - Have them fill equally to have even spacing - Always have spacing and anything else “Use Standard Value” - Do a grid by putting stack views in stack view - To pin relationships on screen, hold control and drag a view to another view (or to the edge of the screen) - Many different relationships you can enforce, names pretty intuitive - Property observers: watch changes to property - willSet has access to newValue property that is going to be set - didSet has access to oldValue that was just overwritten - Computed properties: do computation instead of storing direct value - get returns calculated value - set does calculation to set it (no set makes it read only) - Access control: protect internal implementations - internal: default, usable by any object in my app or framework - private(set): this property is readable outside this object, but not settable - private: only callable (read or write) to from within that object - fileprivate: accessible by any code in this source file - public: (frameworks only) can be used by objects outside this framework - open: (frameworks only) public and objects outside framework can overwrite/subclass it - Good strategy is to mark everything private at first and then open things up as needed - When you have multiple MVC’s, typically one MVC is a part of the View of another - Extensions: add methods/properties to an existing class/struct/enum even if you don’t have the source code for it - Can’t overwrite/re-implement existing methods - Properties that you add must be computed - Range - CountableRange for float: for i in stride(from: 0.0, through: 15.0, by: 0.3) - Tuple - Just throw parentheses around some types or values - Can unpack them - Can have named parameters in tuple - Can use tuple as a return value if you want to have a function return multiple values - Optional - Is an enum - Enum - enum Direction {

-

-

case north case east case south case west

} Enum properties in swift can have associated data - Let menuItem = FastFoodMenuItem.hamburger(patties: 2) Switch to get data - Switch menuItem { - case .hamburger(let pattyCount): print(“burger with \(pattyCount) patties”) - case .otherThing: break - default: print(“this covers things I didn’t mention) - } Can have funcs and vars (computed only, no storage), common to switch on self to figure things out

Lecture 4 4/10/19: - Lazy properties can’t have observers - Important method viewDidLoad (must override it and call the super) - Does things once the view loads (outlets have all been wired up) - Great place to set up model! - Use “!” after a property to have it as an implicitly unwrapped optional - Don’t override init method in controller - Optionals are just enums with a case of being type nil or of some other type (with associated data) - enum Optional { - case none - case some() - } - Two places where you should check implicitly unwrapped optionals (outlets) to see if they’re nil - Property observers being initialized maybe before viewDidLoad - In updateViewFromModel - Memory management - strong: normal reference counting, don’t get rid of it from heap - weak: keep it in heap, but if no one else if pointing to it then you can delete it - If it is deleted it will be nil, so it has to be an optional - unowned: don’t reference count this; crash if I’m wrong - “I know what I’m doing, don’t keep track of this part” - If you have a function in a struct that’s going to change some data in the struct, you have to mark it as mutating - Protocols are a type that is a declaration of functionality only

-

-

-

Has no data storage of any kind Provides multiple inheritance Help express API more concisely Helps define a more narrow set of functions that will be used in a class/controller Lists the function/var declarations that get touched Great for mandating behavior Helps to share certain functionalities for disparate types Can use it to provide some default functionalities too Is a TYPE and can be used anywhere else you would use a type (says that that thing has to implement a certain few functions and variables) - Protocols that you list as inheriting from in declaration means that you must also implement those other inherited protocols too - To declare vars as part of protocol, must provide whether you can get and/or set - Funcs should be declared mutating if they do that - Don’t have to do this if you limit only classes to be able to implement it by saying it inherits from class - Can also have initializers with certain params To implement a protocol, put them after inheritance in declaration of class and then implement their funcs/vars - If an init is required, mark it as required (otherwise subclasses may not conform) - Can add conformance to protocol in an extension NSAttributedString is a String with attributes attached to each character - Basically an object that pairs a string and a dictionary of attributes for each Character - Let attributes: [NSAttributedString.Key : Any] = [.strokeColor : UIColor.orange, .strokeWidth : 5.0] - Swift style would be to do this with an enum with associated values, but they haven’t updated it lol - Let attribText = NSAttributedString(string: “my text”, attributes: attributes)

Lecture 5 4/15/19: - Ranges have a method called filter that takes a function - Can pass function as a closure - can’t have internal and external parameter names - Can get rid of arguments and return type and refer to parameters as $0, $1, etc - If only 1 line then you don’t even need to say return - Ranges also have forEach method that takes a function - Map is similar to filter but creates a new array with those changes made - To extend Array, you need something that will work for whatever the type stored in the array is - Definition says struct Array - Element is a type alias for whatever type is stored in array so we can use that! - To extend array only for int can say extension Array where Element: Int { }

-

-

-

-

-

Typically would put extensions grouped in files away from rest of code, not at bottom of other file Advanced use of protocols - “Multiple inheritance” let's CountableRange implement Sequence, Collection, and other protocols - Extensions to protocols can have code, so we can make protocols have new methods and give subclasses shared functionality through default implementations Functional programming focuses on behavior of data structures more so than storage Can’t index strings by int because Characters can be composed of multiple unicode characters - Special String.Index class used for indexing - Easiest to get index with startIndex, endIndex, firstIndex(of:) and then getting an offset from an index with index(String.Index, offsetBy: Int) - This index function is generic and will return an int or a String.Index or something else depending on what it should be - A String is a RangeReplaceableCollection of Characters - RRC covers String, Array, etc To avoid being typed, use Any (or AnyObject, which can only be a class) - You’ll see it in places that are Objective-C compatible - If you want an array of different types, you could say [Any] but don’t! Instead find what those things have in common and make it an array of an enum or protocol - To use a variable of type Any, we must convert it to a known type by type casting - Use as? keyword to try to convert to another type (nil if it doesn’t succeed) Can also use as? to cast other things like for downcasting, etc For basic, small user settings, use UserDefaults to store Property List data - Property List is any combo of Array, Dictionary, String, Date, Data, or number - Get reference to it with defaults.UserDefaults.standard (one of these for your whole app) - To avoid needing to get something with basic object(forKey:) -> Any? Method and then doing as?, there are better APIs for double(forKey:) -> Double, etc Asynchronous api will have closures that take an extra parameter for an optional error For non async, methods throw errors if something fails - Indicated with “throws” keyword at the end - Then when calling you need to catch with do { try throwableFunc() } catch let error { error.doSomething() } - Can also do try! throwableFunc() but that crashes the program if it throws - try? will return nil if there’s an error which is sometimes used too

Lecture 6 4/17/19: - Have thing implement protocol CustomStringConvertible with description computed property to print things out in a certain way - Have enums implement CaseIterable to iterate through allCases

-

-

-

-

-

-

Need to add some special line to return an AllCases type if you have associated data with enum - First typealias AllCases to tell it what the type is (often array of that enum type) - Then add things to the allCases var to cover all cases Views are UIView subclasses - Represents a rectangular area - Hierarchical - if it is in another view it has a superview and can have multiple subviews - Those later in subviews array are on top of earlier ones - Default is to trim subviews to bounds of superview - UIWindow is very top view - whole screen, don’t pay much attention to it - Can change hierarchy graphically or in code - In ViewController, view var is the highest level view that you can use Initializing a UIView - For UIView you often need some inits - init(frame: CGRect) called if UIView is created in code - init(coder: NSCoder) called if created in storyboard - Need to implement both if you’re making a custom view Drawing coordinate system - Always uses CGFloat for coordinates - Describe points with CGPoint, sixe with CGSize - CGRect constructor takes point and size - Lots of methods to test if rectangles intersect - Origin is top left - Units are points, not pixels because number of pixels varies - Can get pixels per point in contentScaleFactor, but doesn’t really matter - var bounds: CGRect tells us how big the bounds of the screen is - var center: CGPoint and var frame: CGRect have nothing to do with our drawing bounds really - they concern where we are within our superview - Use bounds to draw things - Use frame/center to position Creating views in code: - Make a frame - Make a label with that frame - Add it to the parent view with view.addSubview To make a custom view - Override draw(rect:) - NEVER CALL DRAW(RECT:) YOURSELF - It will be called automatically - Call setNeedsDisplay() if your thing changes and you need to tell the system it needs to redraw it - Either get a drawing context and tell it what to draw or create a path of drawing using UIBezierPath class

-

-

-

-

-

Get context with UIGraphicsGetCurrentContext() Then create paths out of lines, arcs, etc Then set drawing attributes like colors/fonts/textures/linewidths/linecaps, etc Then stroke or fill the given path Define path with UIBezierPath: - let path = UIBezierPath() - path.move(to: CGPoint) - path.addLine(to: CGPoint) - path.close() To clip your drawing to inside the path you can say addClip - Clips forever, but ways around that - To draw with transparency set opaque = false - Otherwise will show up as black - Can set transparency of entire view with UIView’s alpha var Underneath the UIView is a drawing mechanism called CALayer - Core animation layer To hide a view without totally removing it from the hierarchy, set the isHidden property To draw in draw(CGRect), use NSAttributedString - Make attr str, then say attrStr.draw(at: CGPoint) to set position of top left - To go back and forth from String vs NSString differences in indexing, use NSRange to take a range and change it to an NSRange Fonts are important - Many different categories of preset fonts that will be standardized across stuff - Can getPreferredFont or something like that to get something fitting - If you’re using something other than a standard preferred font - First, get metrics for some font with UIFontMetrics(forTextStyle:) - Then say that you’re scaling that font by some amount - systemFont shows up on buttons automatically Draw images with UIImageView, or with UIImage(named:) to get it in the draw(CGRect) method - Put these image files in Assets.xcassets file - Can also construct UIImage from contents of a file in memory or from Data (raw bits) or from drawing it By default, when UIView’s bounds change, there is no redraw - Try to make views draw regardless of specific bounds - System tries to just stretch stuff, but that’s not what we always want - contentMode of view can be to scale, to just place somewhere, or to redraw things - 2nd most important func to override (other than draw) is layoutSubviews() - Each time, call super and then reposition subview’s frames based on new bounds

Lecture 7 4/22/19: - Controller’s job is to interpret the model for the view

-

Convenience initializer for things like UILabel() infer you mean UILabel(frame: CGRect.zero) Always be ready to change bounds of things in override func layoutSubviews() to respond to changing orientation/etc If you want a label to make itself as small as possible, say label.frame.size = label.sizeThatFits(UIView. layoutFittingCompressedSize) UILabel defaults to putting all text on one line, but can set numberOfLines param to whatever you want (0 will use as many as needed) Add @IBDesignable to beginning of UIView subclass to be able to see changes in interface builder To listen to changes in accessibility settings, override traitCollectionDidChange and then say setNeedsLayout() -- don’t directly call layoutSubview!!! Can put lower and higher resolution versions of images, denote higher res with @2x To make images show in IB, use UIImage(named: name, in: Bundle(for: self.classForCoder), compatibleWith: traitCollection)x

Lecture 8 4/24/19: - UITabBarController let's the user choose between different MVCs - UISplitViewController puts 2 MVCs side by side - only for iPad and iPhone _+ in landscape - Have “Master” on one side that controls what shows in “Detail” on other side - UINavigationController pushes and pops MVCs off a stack - When we push something on, we create a new MVC, when we pop off we destroy it - sub-MVCs live in viewControllers property (array of UIViewControllers) - Every view controller has properties tabBarController?, splitViewController?, navigationController? - Can manually call functions pushViewController and popViewController, but normally we won’t call these directly and instead we’ll use Segues - When making something work for iPad and iPhone with UISplitView, insert a NavigationController before detail (control drag to things to link them up) - Segues - Types - Show - pushes in a navigation controller, otherwise does a modal - Show detail - push in nav, shows detail in split - Modal - take over entire screen - Popover - make MVC appear in little popover window - Always create a new MVC - Set them up with more ctrl-drag - Need to give that segue in the storyboard an identifier name that you can use in code to manually perform a segue, or prepare for a segue

-

-

Instigating view controller can prepare destination view controller in function prepare(for segue:sender:) where segue has identifier and destination properties - NOTE: all that preparation happens before outlets are set in the destination To change name of ViewController, refactor: select what you want to rename, cmd-click, rename

Lecture 9 4/29/19: - Timer takes a closure and an amount of time and executes code after a certain amount of time - Timing not necessarily exact - Can give it a certain tolerance to allow phone to save battery and only do it when it has something else to do too - Store in weak var so it leaves heap once it’s done going off - Call invalidate() to stop a repeating timer - UIView Animation - changes to certain UIView properties can be animated over time (frame/center, bounds, transform, alpha, background color) - UIViewPropertyAnimator can be done with runningPropertyAnimator(withDuration:delay:options:animations:completion:) - Lots of animation options, often use a curve thing to make speed start/finish slow - UIView also has a transition function that animates going from one to another, can do flipping and more from one view to another - Dynamic Animation let you set physics that UIViews will obey - Make UIDynamicAnimation in superview that contains everything you want to obey that - Then you have to add items to that animator - Other dynamis behaviors: gravity, attachment, collision, snap, push, meta behavior - Call addChildBehavior(UIDynamicBehavior) to add behavior for child - UIDynamicBehavior’s action property gets called a lot so make it efficient - Animator delegate will let you know when dynamicAnimatorDidPause and dynamicAnimatorWillResume - Closure capturing - Can define local variables at the start of the closure - Can also make them weak or even unowned - Helps to break memory cycles where a couple things are keeping each other in memory - When you get animations, set it to take a long time, then test to make sure it still works with long animations

Lecture 10 5/1/19: - Delegator is just something that sends messages (need to implement a protocol) - UIDynamicAnimatorDelegate required implementing didPause and willResume - They’re obj protocols so it won’t make us implement them though - View controller lifecycle: creation, prep for segue, outlet setting, view loads, appears, disappears (repeatedly?), layoutSubviews throughout - viewDidLoad happens after prepare and outlet setting - Can update UI from model unless it uses geometry stuff - viewWillAppear happens right before appearing on screen - Can do geometry stuff here - Can be called repeatedly, whereas viewDidLoad is more just once - viewDidAppear happens right after things appear - Good time to do things expensive like network fetches - Show spinning wheel while waiting for expensive thing to arrive - Do backgroun...


Similar Free PDFs
CS193P Notes
  • 17 Pages
Notes
  • 18 Pages
Notes
  • 12 Pages
Notes
  • 61 Pages
Notes
  • 35 Pages
Notes
  • 19 Pages
Notes
  • 70 Pages
Notes
  • 6 Pages
Notes
  • 35 Pages
Notes
  • 29 Pages
Notes
  • 70 Pages
Notes
  • 6 Pages
Notes
  • 19 Pages
Notes
  • 32 Pages
Notes
  • 28 Pages