This document summarizes key concepts about views in iOS, including:
1) Views represent rectangular areas for drawing and handling touch, arranged hierarchically with one superview and multiple subviews.
2) The view hierarchy is constructed visually in Xcode or programmatically by adding/removing subviews.
3) A view's coordinate system for drawing is defined by its bounds property, while its frame and center describe its position within its superview.
4) Common data structures like CGPoint, CGSize, CGRect, and CGFloat are used to represent points, sizes, rectangles and floating point values for view geometry.
(5) cpp dynamic memory_arrays_and_c-stringsNico Ludwig
Check out these exercises: http://de.slideshare.net/nicolayludwig/5-cpp-dynamic-memoryarraysandcstringsexercises
- The Heap: Dynamic Memory and dynamic Array Allocation
- Automatic versus Dynamic Arrays
- A Glimpse of the Topic "Stack versus Heap"
-- "Geometric" Properties of the Heap and the Stack
- Lost Pointers and Memory Leaks
- Advanced C-strings: Buffers, Concatenation and Formatting
Some of you may know that we have recently released version 6.00 of our analyzer, that now has C# support. The ability to scan C# projects increases the number of open-source projects we can analyze. This article is about one such check. This time it is a project, developed by Sony Computer Entertainment (SCEI).
C++11 (formerly known as C++0x) is the new C++ language standard. Dave Abraha...yaevents
Dave Abrahams, BoostPro Computing
He is a founding member of Boost.org and an active participant in the ISO C++ standards committee. His broad range of experience in the computer industry includes shrink-wrap software development, embedded systems design and natural language processing. He has authored eight Boost libraries and has made contributions to numerous others. Dave made his mark on C++ standardization by developing a conceptual framework for understanding exception-safety and applying it to the C++ standard library. He created the first exception-safe standard library implementation and, with Greg Colvin, drafted the proposals that eventually became the standard library’s exception safety guarantees.
Presentation topic:
C++11 (formerly known as C++0x) is the new C++ language standard. Dave Abrahams, BoostPro Computing.
Key points:
The ISO C++ standardization committee has just unanimously approved its final draft international standard, and it's chock full of new features. Though a few of the features have been available for years, some are brand new, and nobody really knows what it's like to program in this new C++ language. As with C++03, Boost.org is expected to take a leading role in exploiting C++11. In this talk, I'll give an overview of the most important new developments.
(5) cpp dynamic memory_arrays_and_c-stringsNico Ludwig
Check out these exercises: http://de.slideshare.net/nicolayludwig/5-cpp-dynamic-memoryarraysandcstringsexercises
- The Heap: Dynamic Memory and dynamic Array Allocation
- Automatic versus Dynamic Arrays
- A Glimpse of the Topic "Stack versus Heap"
-- "Geometric" Properties of the Heap and the Stack
- Lost Pointers and Memory Leaks
- Advanced C-strings: Buffers, Concatenation and Formatting
Some of you may know that we have recently released version 6.00 of our analyzer, that now has C# support. The ability to scan C# projects increases the number of open-source projects we can analyze. This article is about one such check. This time it is a project, developed by Sony Computer Entertainment (SCEI).
C++11 (formerly known as C++0x) is the new C++ language standard. Dave Abraha...yaevents
Dave Abrahams, BoostPro Computing
He is a founding member of Boost.org and an active participant in the ISO C++ standards committee. His broad range of experience in the computer industry includes shrink-wrap software development, embedded systems design and natural language processing. He has authored eight Boost libraries and has made contributions to numerous others. Dave made his mark on C++ standardization by developing a conceptual framework for understanding exception-safety and applying it to the C++ standard library. He created the first exception-safe standard library implementation and, with Greg Colvin, drafted the proposals that eventually became the standard library’s exception safety guarantees.
Presentation topic:
C++11 (formerly known as C++0x) is the new C++ language standard. Dave Abrahams, BoostPro Computing.
Key points:
The ISO C++ standardization committee has just unanimously approved its final draft international standard, and it's chock full of new features. Though a few of the features have been available for years, some are brand new, and nobody really knows what it's like to program in this new C++ language. As with C++03, Boost.org is expected to take a leading role in exploiting C++11. In this talk, I'll give an overview of the most important new developments.
Sharing thoughts about migrating from Objective-C to Swift.
Why, How and What. This presentation was held on Munich iOS Meetup 12/02/15. http://www.meetup.com/de/The-Munich-iOS-Developers-Meetup/events/226586543/
Of complicacy of programming, or won't C# save us?PVS-Studio
Programming is hard. I hope no one would argue that. But the topic of new programming languages, or more exactly, search of a "silver bullet" is always highly popular with software developers. The most "trendy" topic currently is superiority of one programming language over the other. For instance, C# is "cooler" than C++. Although holy wars are not the reason why I'm writing this post, still it is a "sore subject" for me. Oh, come on, C#/lisp/F#/Haskell/... won't let you write a smart application that would interact with the outer world and that's all. All the elegance will disappear as soon as you decide to write some real soft and not a sample "in itself".
In this talk, I'm presenting an alternative approach to thinking about UI and navigation on iOS - one that is declarative and that I find easy to reason about in a big application. I did live coding and the link is on the last slide. Enjoy!
React-Native components are awesome. But you can also extend the library yourself by creating a native component, using a bridge between the platform API (iOS, Android) and Javascript.
Demo code is here: https://github.com/jgrancher/talk-rncc
Just how different is "Modern C++" from "legacy C++"? Is my codebase ready for C++17? Do I need a full rewrite of my app to modernize my code? If you're looking for answers to some of these questions, join us for a session on how to effectively leverage modern C++17 features in your existing C++ projects; and no, you don't need to rewrite your app.
Just how different is "Modern C++" from "legacy C++"? Is my codebase ready for C++17? Do I need a full rewrite of my app to modernize my code? If you're looking for answers to some of these questions, join us for a session on how to effectively leverage modern C++17 features in your existing C++ projects; and no, you don't need to rewrite your app.
Consequences of using the Copy-Paste method in C++ programming and how to dea...Andrey Karpov
I create the PVS-Studio analyzer detecting errors in source code of C/C++/C++0x software. So I have to review a large amount of source code of various applications where we detected suspicious code fragments with the help of PVS-Studio. I have collected a lot of examples demonstrating that an error occurred because of copying and modifying a code fragment. Of course, it has been known for a long time that using Copy-Paste in programming is a bad thing. But let's try to investigate this problem closely instead of limiting ourselves to just saying "do not copy the code".
ChakraCore: analysis of JavaScript-engine for Microsoft EdgePVS-Studio
On the JSConf US conference in December 2015 the developers announced that they were planning to make open the source code of Chakra key components, a JavaScript-engine, operating in Microsoft Edge. Recently the ChackraCore source code became available under the MIT license in the corresponding repository on GitHub. In this article you will find interesting code fragments that were detected with the help of PVS-Studio code analyzer.
MVC Puree - Approaches to MVC with UmbracoAndy Butland
Slides from talk given at the Umbraco Codegarden Festival 2014 on using MVC with Umbraco, with a focus on the use of route hijacking, strongly typed models and mapping.
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...Doug Jones
We rarely dive into current programming languages, touting the next new framework or the new features that will be out next year. This is about JavaScript the language as it exists today, what I picked up in going from C# to JS, and what C# picked up from JS along the way as well. It is based on Douglas Crockford's seminal book "JavaScript: The Good Parts".
Slides from my "Swift, Swiftly" session at Øredev 2014.
Revealed by Apple in June of this year, the Swift programming language has already established itself as a huge leap forward for iOS and OS X developers. Learn the ins and outs of this new language, see how it compares to other modern OO languages, and hear about how Apple developers are using Swift to achieve new levels of productivity and efficiency.
Full video available: http://oredev.org/2014/sessions/swift-swiftly
Sharing thoughts about migrating from Objective-C to Swift.
Why, How and What. This presentation was held on Munich iOS Meetup 12/02/15. http://www.meetup.com/de/The-Munich-iOS-Developers-Meetup/events/226586543/
Of complicacy of programming, or won't C# save us?PVS-Studio
Programming is hard. I hope no one would argue that. But the topic of new programming languages, or more exactly, search of a "silver bullet" is always highly popular with software developers. The most "trendy" topic currently is superiority of one programming language over the other. For instance, C# is "cooler" than C++. Although holy wars are not the reason why I'm writing this post, still it is a "sore subject" for me. Oh, come on, C#/lisp/F#/Haskell/... won't let you write a smart application that would interact with the outer world and that's all. All the elegance will disappear as soon as you decide to write some real soft and not a sample "in itself".
In this talk, I'm presenting an alternative approach to thinking about UI and navigation on iOS - one that is declarative and that I find easy to reason about in a big application. I did live coding and the link is on the last slide. Enjoy!
React-Native components are awesome. But you can also extend the library yourself by creating a native component, using a bridge between the platform API (iOS, Android) and Javascript.
Demo code is here: https://github.com/jgrancher/talk-rncc
Just how different is "Modern C++" from "legacy C++"? Is my codebase ready for C++17? Do I need a full rewrite of my app to modernize my code? If you're looking for answers to some of these questions, join us for a session on how to effectively leverage modern C++17 features in your existing C++ projects; and no, you don't need to rewrite your app.
Just how different is "Modern C++" from "legacy C++"? Is my codebase ready for C++17? Do I need a full rewrite of my app to modernize my code? If you're looking for answers to some of these questions, join us for a session on how to effectively leverage modern C++17 features in your existing C++ projects; and no, you don't need to rewrite your app.
Consequences of using the Copy-Paste method in C++ programming and how to dea...Andrey Karpov
I create the PVS-Studio analyzer detecting errors in source code of C/C++/C++0x software. So I have to review a large amount of source code of various applications where we detected suspicious code fragments with the help of PVS-Studio. I have collected a lot of examples demonstrating that an error occurred because of copying and modifying a code fragment. Of course, it has been known for a long time that using Copy-Paste in programming is a bad thing. But let's try to investigate this problem closely instead of limiting ourselves to just saying "do not copy the code".
ChakraCore: analysis of JavaScript-engine for Microsoft EdgePVS-Studio
On the JSConf US conference in December 2015 the developers announced that they were planning to make open the source code of Chakra key components, a JavaScript-engine, operating in Microsoft Edge. Recently the ChackraCore source code became available under the MIT license in the corresponding repository on GitHub. In this article you will find interesting code fragments that were detected with the help of PVS-Studio code analyzer.
MVC Puree - Approaches to MVC with UmbracoAndy Butland
Slides from talk given at the Umbraco Codegarden Festival 2014 on using MVC with Umbraco, with a focus on the use of route hijacking, strongly typed models and mapping.
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...Doug Jones
We rarely dive into current programming languages, touting the next new framework or the new features that will be out next year. This is about JavaScript the language as it exists today, what I picked up in going from C# to JS, and what C# picked up from JS along the way as well. It is based on Douglas Crockford's seminal book "JavaScript: The Good Parts".
Slides from my "Swift, Swiftly" session at Øredev 2014.
Revealed by Apple in June of this year, the Swift programming language has already established itself as a huge leap forward for iOS and OS X developers. Learn the ins and outs of this new language, see how it compares to other modern OO languages, and hear about how Apple developers are using Swift to achieve new levels of productivity and efficiency.
Full video available: http://oredev.org/2014/sessions/swift-swiftly
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
Acetabularia Information For Class 9 .docxvaibhavrinwa19
Acetabularia acetabulum is a single-celled green alga that in its vegetative state is morphologically differentiated into a basal rhizoid and an axially elongated stalk, which bears whorls of branching hairs. The single diploid nucleus resides in the rhizoid.
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
3. CS193p
Fall 2017-18
Thrown Errors
In Swift, methods can throw errors
You will always know that can throw because they’ll have the keyword throws on the end.
func save() throws
You must put calls to functions like this in a do { } block and use the word try to call them.
do {
try context.save()
} catch let error {
// error will be something that implements the Error protocol, e.g., NSError
// usually these are enums that have associated values to get error details
throw error // this would re-throw the error (only ok if the method we are in throws)
}
If you are certain a call will not throw, you can force try with try! …
try! context.save() // will crash your program if save() actually throws an error
Or you can conditionally try, turning the return into an Optional (which will be nil if fail) …
let x = try? errorProneFunctionThatReturnsAnInt() // x will be Int?
4. CS193p
Fall 2017-18
Any & AnyObject are special types
These types used to be commonly used for compatibility with old Objective-C APIs
But not so much anymore in iOS 11 since those old Objective-C APIs have been updated
(though we did see it with NSAttributedString)
Variables of type Any can hold something of any type (AnyObject holds classes only).
Swift is a strongly typed language, though, so you can’t invoke a method on an Any.
You have to convert it into a concrete type first.
One of the beauties of Swift is its strong typing, so generally you want to avoid Any.
Any & AnyObject
5. CS193p
Fall 2017-18
Where will you see it in iOS?
We already saw it in NSAttributedString.
let attributes: [NSAttributedStringKey:Any] = …
The attributes of an NSAttributedString can be different things (UIColor, UIFont, etc.).
So the type Any was used as the type of the values in the attributes Dictionary.
Sometimes (rarely) Any will be the type of a function’s argument.
Here’s a UIViewController method that includes a sender (which can be of any type).
func prepare(for segue: UIStoryboardSegue, sender: Any?)
The sender is the thing that caused this “segue” (i.e., a move to another MVC) to occur.
The sender might be a UIButton or a UITableViewCell or some custom thing in your code.
It’s an Optional because it’s okay for a segue to happen without a sender being specified.
These are old Objective-C API.
In Swift we would probably would have used an enum with associated data or a protocol.
Any & AnyObject
6. CS193p
Fall 2017-18
Don’t use Any in this course
You can, of course, call iOS API that uses it.
But don’t use it for any of your own internal data structure work.
Any & AnyObject
7. CS193p
Fall 2017-18
How do we use a variable of type Any?
We can’t use it directly (since we don’t know what type it really is).
Instead, we must convert it to another, known type.
Conversion is done with the as? keyword in Swift.
This conversion might not be possible, so the conversion generates an Optional.
You can also check to see if something can be converted with the is keyword (true/false).
We almost always use as? it with if let …
let unknown: Any = … // we can’t send unknown a message because it’s “typeless”
if let foo = unknown as? MyType {
// foo is of type MyType in here
// so we can invoke MyType methods or access MyType vars in foo
// if unknown was not of type MyType, then we’ll never get here
}
Any & AnyObject
8. CS193p
Fall 2017-18
By the way, casting with as? is not just for Any & AnyObject
You can cast any type with as? into any other type that makes sense.
Mostly this would be casting an object from one of its superclasses down to a subclass.
But it could also be used to cast any type to a protocol it implements (more on this later).
Example of “downcasting” from a superclass down to a subclass …
let vc: UIViewController = ConcentrationViewController()
The type of vc is UIViewController (because we explicitly typed it to be).
And the assignment is legal because a ConcentrationViewController is a UIViewController.
But we can’t say, for example, vc.flipCard(…), since vc is typed as a UIViewController.
However, if we cast vc to be a ConcentrationViewController, then we can use it …
if let cvc = vc as? ConcentrationViewController {
cvc.flipCard(…) // this is okay
}
Casting
9. CS193p
Fall 2017-18
Other Interesting Classes
NSObject
Base class for all Objective-C classes
Some advanced features will require you to subclass from NSObject (and it can’t hurt to do so)
NSNumber
Generic number-holding class (i.e., reference type)
let n = NSNumber(35.5) or let n: NSNumber = 35.5
let intified: Int = n.intValue // also doubleValue, boolValue, etc.
Date
Value type used to find out the date and time right now or to store past or future dates
See also Calendar, DateFormatter, DateComponents
If you are displaying a date in your UI, there are localization ramifications, so check these out!
Data
A value type “bag o’ bits”. Used to save/restore/transmit raw data throughout the iOS SDK.
10. CS193p
Fall 2017-18
Views
A view (i.e. UIView subclass) represents a rectangular area
Defines a coordinate space
For drawing
And for handling touch events
Hierarchical
A view has only one superview … var superview: UIView?
But it can have many (or zero) subviews … var subviews: [UIView]
The order in the subviews array matters: those later in the array are on top of those earlier
A view can clip its subviews to its own bounds or not (the default is not to)
UIWindow
The UIView at the very, very top of the view hierarchy (even includes status bar)
Usually only one UIWindow in an entire iOS application … it’s all about views, not windows
11. CS193p
Fall 2017-18
Views
The hierarchy is most often constructed in Xcode graphically
Even custom views are usually added to the view hierarchy using Xcode
But it can be done in code as well
func addSubview(_ view: UIView)// sent to view’s (soon to be) superview
func removeFromSuperview() // sent to the view you want to remove (not its superview)
Where does the view hierarchy start?
The top of the (useable) view hierarchy is the Controller’s var view: UIView.
This simple property is a very important thing to understand!
This view is the one whose bounds will change on rotation, for example.
This view is likely the one you will programmatically add subviews to (if you ever do that).
All of your MVC’s View’s UIViews will have this view as an ancestor.
It’s automatically hooked up for you when you create an MVC in Xcode.
12. CS193p
Fall 2017-18
Initializing a UIView
As always, try to avoid an initializer if possible
But having one in UIView is slightly more common than having a UIViewController initializer
A UIView’s initializer is different if it comes out of a storyboard
init(frame: CGRect) // initializer if the UIView is created in code
init(coder: NSCoder) // initializer if the UIView comes out of a storyboard
If you need an initializer, implement them both …
func setup() { … }
override init(frame: CGRect) { // a designated initializer
super.init(frame: frame)
setup() // might have to be before super.init
}
required init?(coder aDecoder: NSCoder) { // a required, failable initializer
super.init(coder: aDecoder)
setup()
}
13. CS193p
Fall 2017-18
Initializing a UIView
Another alternative to initializers in UIView …
awakeFromNib() // this is only called if the UIView came out of a storyboard
This is not an initializer (it’s called immediately after initialization is complete)
All objects that inherit from NSObject in a storyboard are sent this
Order is not guaranteed, so you cannot message any other objects in the storyboard here
14. CS193p
Fall 2017-18
Coordinate System Data Structures
CGFloat
Always use this instead of Double or Float for anything to do with a UIView’s coordinate system
You can convert to/from a Double or Float using initializers, e.g., let cgf = CGFloat(aDouble)
CGPoint
Simply a struct with two CGFloats in it: x and y.
var point = CGPoint(x: 37.0, y: 55.2)
point.y -= 30
point.x += 20.0
CGSize
Also a struct with two CGFloats in it: width and height.
var size = CGSize(width: 100.0, height: 50.0)
size.width += 42.5
size.height += 75
15. CS193p
Fall 2017-18
Coordinate System Data Structures
CGRect
A struct with a CGPoint and a CGSize in it …
struct CGRect {
var origin: CGPoint
var size: CGSize
}
let rect = CGRect(origin: aCGPoint, size: aCGSize) // there are other inits as well
Lots of convenient properties and functions on CGRect like …
var minX: CGFloat // left edge
var midY: CGFloat // midpoint vertically
intersects(CGRect) -> Bool // does this CGRect intersect this other one?
intersect(CGRect) // clip the CGRect to the intersection with the other one
contains(CGPoint) -> Bool // does the CGRect contain the given CGPoint?
… and many more (make yourself a CGRect and type . after it to see more)
16. CS193p
Fall 2017-18
View Coordinate System
Origin is upper left
Units are points, not pixels
Pixels are the minimum-sized unit of drawing your device is capable of
Points are the units in the coordinate system
Most of the time there are 2 pixels per point, but it could be only 1 or even 3
How many pixels per point are there? UIView’s var contentScaleFactor: CGFloat
The boundaries of where drawing happens
var bounds: CGRect // a view’s internal drawing space’s origin and size
This is the rectangle containing the drawing space in its own coordinate system
It is up to your view’s implementation to interpret what bounds.origin means (often nothing)
Where is the UIView?
var center: CGPoint // the center of a UIView in its superview’s coordinate system
var frame: CGRect // the rect containing a UIView in its superview’s coordinate system
(0,0) increasing xincreasingy
(500, 35)
17. CS193p
Fall 2017-18
bounds vs frame
Use frame and/or center to position a UIView
These are never used to draw inside a view’s coordinate system
You might think frame.size is always equal to bounds.size, but you’d be wrong …
View A
View
B
300, 225
200
250
0,0
320
320
140, 65
Views can be rotated (and scaled and translated)
View B’s bounds = ((0,0),(200,250))
View B’s frame = ((140,65),(320,320))
View B’s center = (300,225)
View B’s middle in its own coordinates is …
(bounds.midX, bounds.midY) = (100, 125)
Views are rarely rotated, but don’t misuse
frame or center anyway by assuming that.
18. CS193p
Fall 2017-18
Most often your views are created via your storyboard
Xcode’s Object Palette has a generic UIView you can drag out
After you do that, you must use the Identity Inspector to changes its class to your subclass
On rare occasion, you will create a UIView via code
You can use the frame initializer … let newView = UIView(frame: myViewFrame)
Or you can just use let newView = UIView() (frame will be CGRect.zero)
Example
let labelRect = CGRect(x: 20, y: 20, width: 100, height: 50)
let label = UILabel(frame: labelRect) // UILabel is a subclass of UIView
label.text = “Hello”
Creating Views
19. CS193p
Fall 2017-18
Most often your views are created via your storyboard
Xcode’s Object Palette has a generic UIView you can drag out
After you do that, you must use the Identity Inspector to changes its class to your subclass
On rare occasion, you will create a UIView via code
You can use the frame initializer … let newView = UIView(frame: myViewFrame)
Or you can just use let newView = UIView() (frame will be CGRect.zero)
Example
let labelRect = CGRect(x: 20, y: 20, width: 100, height: 50)
let label = UILabel(frame: labelRect) // UILabel is a subclass of UIView
label.text = “Hello”
// assuming this code is in a UIViewController (and thus the var view is the root view)
view.addSubview(label)
Creating Views
Hello
20. CS193p
Fall 2017-18
Custom Views
When would I create my own UIView subclass?
I want to do some custom drawing on screen
I need to handle touch events in a special way (i.e. different than a button or slider does)
We’ll talk about handling touch events in a bit. First we’ll focus on drawing.
To draw, just create a UIView subclass and override draw(CGRect)
override func draw(_ rect: CGRect)
You can draw outside the rect, but it’s never required to do so.
The rect is purely an optimization.
It is our UIView’s bounds that describe the entire drawing area (the rect is a subarea).
NEVER call draw(CGRect)!! EVER! Or else!
Instead, if you view needs to be redrawn, let the system know that by calling …
setNeedsDisplay()
setNeedsDisplay(_ rect: CGRect) // rect is the area that needs to be redrawn
iOS will then call your draw(CGRect) at an appropriate time
21. CS193p
Fall 2017-18
Custom Views
So how do I implement my draw(CGRect)?
You can either get a drawing context and tell it what to draw, or …
You can create a path of drawing using UIBezierPath class
Core Graphics Concepts
1. You get a context to draw into (other contexts include printing, off-screen buffer, etc.)
The function UIGraphicsGetCurrentContext() gives a context you can use in draw(CGRect)
2. Create paths (out of lines, arcs, etc.)
3. Set drawing attributes like colors, fonts, textures, linewidths, linecaps, etc.
4. Stroke or fill the above-created paths with the given attributes
UIBezierPath
Same as above, but captures all the drawing with a UIBezierPath instance
UIBezierPath automatically draws in the “current” context (preset up for you in draw(CGRect))
UIBezierPath has methods to draw (lineto, arcs, etc.) and to set attributes (linewidth, etc.)
Use UIColor to set stroke and fill colors
UIBezierPath has methods to stroke and/or fill
23. CS193p
Fall 2017-18
Create a UIBezierPath
let path = UIBezierPath()
Move around, add lines or arcs to the path
path.move(to: CGPoint(80, 50))
Defining a Path
24. CS193p
Fall 2017-18
Create a UIBezierPath
let path = UIBezierPath()
Move around, add lines or arcs to the path
path.move(to: CGPoint(80, 50))
path.addLine(to: CGPoint(140, 150))
Defining a Path
25. CS193p
Fall 2017-18
Create a UIBezierPath
let path = UIBezierPath()
Move around, add lines or arcs to the path
path.move(to: CGPoint(80, 50))
path.addLine(to: CGPoint(140, 150))
path.addLine(to: CGPoint(10, 150))
Defining a Path
26. CS193p
Fall 2017-18
Create a UIBezierPath
let path = UIBezierPath()
Move around, add lines or arcs to the path
path.move(to: CGPoint(80, 50))
path.addLine(to: CGPoint(140, 150))
path.addLine(to: CGPoint(10, 150))
Close the path (if you want)
path.close()
Defining a Path
27. CS193p
Fall 2017-18
Create a UIBezierPath
let path = UIBezierPath()
Move around, add lines or arcs to the path
path.move(to: CGPoint(80, 50))
path.addLine(to: CGPoint(140, 150))
path.addLine(to: CGPoint(10, 150))
Close the path (if you want)
path.close()
Now that you have a path, set attributes and stroke/fill
Defining a Path
28. CS193p
Fall 2017-18
Create a UIBezierPath
let path = UIBezierPath()
Move around, add lines or arcs to the path
path.move(to: CGPoint(80, 50))
path.addLine(to: CGPoint(140, 150))
path.addLine(to: CGPoint(10, 150))
Close the path (if you want)
path.close()
Now that you have a path, set attributes and stroke/fill
UIColor.green.setFill() // note setFill is a method in UIColor, not UIBezierPath
UIColor.red.setStroke() // note setStroke is a method in UIColor, not UIBezierPath
path.linewidth = 3.0 // linewidth is a property in UIBezierPath, not UIColor
path.fill() // fill is a method in UIBezierPath
Defining a Path
29. CS193p
Fall 2017-18
Create a UIBezierPath
let path = UIBezierPath()
Move around, add lines or arcs to the path
path.move(to: CGPoint(80, 50))
path.addLine(to: CGPoint(140, 150))
path.addLine(to: CGPoint(10, 150))
Close the path (if you want)
path.close()
Now that you have a path, set attributes and stroke/fill
UIColor.green.setFill() // note setFill is a method in UIColor, not UIBezierPath
UIColor.red.setStroke() // note setStroke is a method in UIColor, not UIBezierPath
path.linewidth = 3.0 // linewidth is a property in UIBezierPath, not UIColor
path.fill() // fill is a method in UIBezierPath
path.stroke() // stroke method in UIBezierPath
Defining a Path
30. CS193p
Fall 2017-18
Drawing
You can also draw common shapes with UIBezierPath
let roundedRect = UIBezierPath(roundedRect: CGRect, cornerRadius: CGFloat)
let oval = UIBezierPath(ovalIn: CGRect)
… and others
Clipping your drawing to a UIBezierPath’s path
addClip()
For example, you could clip to a rounded rect to enforce the edges of a playing card
Hit detection
func contains(_ point: CGPoint) -> Bool // returns whether the point is inside the path
The path must be closed. The winding rule can be set with usesEvenOddFillRule property.
Etc.
Lots of other stuff. Check out the documentation.
31. CS193p
Fall 2017-18
UIColor
Colors are set using UIColor
There are type (aka static) vars for standard colors, e.g. let green = UIColor.green
You can also create them from RGB, HSB or even a pattern (using UIImage)
Background color of a UIView
var backgroundColor: UIColor // we used this for our Concentration buttons
Colors can have alpha (transparency)
let semitransparentYellow = UIColor.yellow.withAlphaComponent(0.5)
Alpha is between 0.0 (fully transparent) and 1.0 (fully opaque)
If you want to draw in your view with transparency …
You must let the system know by setting the UIView var opaque = false
You can make your entire UIView transparent …
var alpha: CGFloat
32. CS193p
Fall 2017-18
Layers
Underneath UIView is a drawing mechanism called CALayer
You usually do not care about this.
But there is some useful API there.
You access a UIView’s “layer” using this var …
var layer: CALayer
The CA in CALayer stands for “Core Animation”.
Mostly we can do animation in a UIView without accessing this layer directly.
But it is where the actual animation functionality of UIView is coming from.
We’ll talk about animation next week.
But CALayer can do some cool non-animation oriented things as well, for example …
var cornerRadius: CGFloat // make the background a rounded rect
var borderWidth: CGFloat // draw a border around the view
var borderColor: CGColor? // the color of the border (if any)
You can get a CGColor from a UIColor using UIColor’s cgColor var.
33. CS193p
Fall 2017-18
View Transparency
What happens when views overlap and have transparency?
As mentioned before, subviews list order determines who is in front
Lower ones (earlier in the array) can “show through” transparent views on top of them
Transparency is not cheap, by the way, so use it wisely
Completely hiding a view without removing it from hierarchy
var isHidden: Bool
An isHidden view will draw nothing on screen and get no events either
Not as uncommon as you might think to temporarily hide a view
34. CS193p
Fall 2017-18
Drawing Text
Usually we use a UILabel to put text on screen
But there are certainly occasions where we want to draw text in our draw(CGRect)
To draw in draw(CGRect), use NSAttributedString
let text = NSAttributedString(string: “hello”) // probably would set some attributes too
text.draw(at: aCGPoint) // or draw(in: CGRect)
let textSize: CGSize = text.size // how much space the string will take up
Accessing a range of characters in an NSAttributedString
NSRange has an init which can handle the String vs. NSString weirdness …
let pizzaJoint = “café pesto”
var attrString = NSMutableAttributedString(string: pizzaJoint)
let firstWordRange = pizzaJoint.startIndex..<pizzaJoint.indexOf(“ “)!
let nsrange = NSRange(firstWordRange, in: pizzaJoint) // convert Range<String.Index>
attrString.addAttribute(.strokeColor, value: UIColor.orange, range: nsrange)
36. CS193p
Fall 2017-18
Fonts
Usually you set fonts in UI elements like UIButton, UILabel, etc.
Be sure to choose a “preferred font” for user content in the Inspector in InterfaceBuilder.
User content is information generated by or requested by the user (not button titles, etc.).
But you might want to set a font in an NSAttributedString too …
Simple way to get a font in code
Get preferred font for a given text style (e.g. body, etc.) using this UIFont type method …
static func preferredFont(forTextStyle: UIFontTextStyle) -> UIFont
Some of the styles (see UIFontDescriptor documentation for more) …
UIFontTextStyle.headline
.body
.footnote
Importantly, the size of the font you get is determined by user settings (esp. for Accessibility).
You’ll want to make sure your UI looks good with all size fonts!
37. CS193p
Fall 2017-18
Fonts
More advanced way …
Choose a specific font by name …
let font = UIFont(name: “Helvetica”, size: 36.0)
You can also use the UIFontDescriptor class to get the font you want.
Now get metrics for the text style you want and scale font to the user’s desired size …
let metrics = UIFontMetrics(forTextStyle: .body) // or UIFontMetrics.default
let fontToUse = metrics.scaledFont(for: font)
38. CS193p
Fall 2017-18
Fonts
There are also “system fonts”
These appear usually on things like buttons.
static func systemFont(ofSize: CGFloat) -> UIFont
static func boldSystemFont(ofSize: CGFloat) -> UIFont
But again, don’t use these for your user’s content. Use preferred fonts for that.
39. CS193p
Fall 2017-18
Drawing Images
There is a UILabel-equivalent for images
UIImageView
But, again, you might want to draw the image inside your draw(CGRect) …
Creating a UIImage object
let image: UIImage? = UIImage(named: “foo”) // note that its an Optional
You add foo.jpg to your project in the Assets.xcassets file (we’ve ignored this so far)
Images will have different resolutions for different devices (all managed in Assets.xcassets)
You can also create one from files in the file system
(But we haven’t talked about getting at files in the file system … anyway …)
let image: UIImage? = UIImage(contentsOfFile: pathString)
let image: UIImage? = UIImage(data: aData) // raw jpg, png, tiff, etc. image data
You can even create one by drawing with Core Graphics
See documentation for UIGraphicsBeginImageContext(CGSize)
40. CS193p
Fall 2017-18
Drawing Images
Once you have a UIImage, you can blast its bits on screen
let image: UIImage = …
image.draw(at point: aCGPoint) // the upper left corner put at aCGPoint
image.draw(in rect: aCGRect) // scales the image to fit aCGRect
image.drawAsPattern(in rect: aCGRect) // tiles the image into aCGRect
41. CS193p
Fall 2017-18
Redraw on bounds change?
By default, when a UIView’s bounds changes, there is no redraw
Instead, the “bits” of the existing image are scaled to the new bounds size
This is often not what you want …
Luckily, there is a UIView property to control this! It can be set in Xcode too.
var contentMode: UIViewContentMode
UIViewContentMode
Don’t scale the view, just place the bits (intact) somewhere …
.left/.right/.top/.bottom/.topRight/.topLeft/.bottomRight/.bottomLeft/.center
Scale the “bits” of the view …
.scaleToFill/.scaleAspectFill/.scaleAspectFit // .scaleToFill is the default
Redraw by calling draw(CGRect) again (costly, but for certain content, better results) …
.redraw
42. CS193p
Fall 2017-18
Layout on bounds change?
What about your subviews on a bounds change?
If your bounds change, you may want to reposition some of your subviews
Usually you would set this up using Autolayout constraints
Or you can manually reposition your views when your bounds change by overriding …
override func layoutSubviews() {
super.layoutSubviews()
// reposition my subviews’s frames based on my new bounds
}