What's new in SwiftUI for iOS 14 – Extended Edition

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] in this video I'm going to walk you through all the major new features for Swift UI in iOS 14 including things like maps and grids and sprite integration paging tab views document Pickers magic move animations and much more it's gonna be awesome and there's stacks of code along the way so you can follow along at home in fact down here in the description you will see timestamps of each of these features covered in the video so you can jump to the bit you care about most enough chat let's get to the code in iOS 14 swift UI adds a new text editor view they're doing multi-line text editing it's different from the older text field for doing single line text editing let's try it out now first things first in your content in view you'll make some state to store the string you want to edit I'll do at state private VAR profile text be equal to enter your bio by default then down here in the body I'll make a navigation view to avoid the safe area and then do text editor bound to the text of dollar profile text and that's it that's my multi-line text editor I press command R I can build and run there we go into your bio rattle nuts and switch to the hardware keyboard I can type in here let's do hello world boom and it writes out smoothly now behind the scenes this thing works just like a text field or regular text view I could say I want to have a font of dot title or large title or have a foreground color of green it's down to you it's just text you can modify it as much as you want to lovely in iOS 14 swift UI gains the power to make grids both horizontally and vertically even better they're lazy which means only when your content Scrolls on to view it gets made not before lazy load your stuff for maximum speed and maximum efficiency let's try it out here the simplest possible grid you can make is some data with numbers so I'll do data is going to be 1 through a thousand and I'm going to map that to some strings I'll do item string interpolation dollar 0 like that and now you go ahead and define your layouts now you either defined columns or rows and the iOS fill in the rest so I'll do columns here I'll say my columns is a single array of a grid item using adaptive spacing with minimum 80 points now adaptive spacing for columns or rows means fill up the space with as many of these cells as you can all I care about is they have a minimum of 80 points in size now in this case I'm doing columns that'll mean a minimum width of 80 points per column and it depends the system how many columns I can squeeze in there based on how big the actual screen is so as our columns there's our data where that in place we can now make our grid I'll say in our body let's scroll down just slightly I'll say that is a scroll view and a scroll view has a lazy V grid with columns being columns and spacing I'll do 20 inside there I'll loop over all our data using ID of dot self the string itself so unique and do item in and I said for each cell just show that item in a text and add a little bit of padding for the horizontal edges for the scroll view so it looks nice and in the screen let's run that back see how it looks in the preview boom there's our grid and press command R so we can see intractably on the simulator see how that looks boom you can see it's managed to squeeze in four columns here if I rotate it'll spit in more columns so now I've got what is that eight there we go lots of columns right here now so it'll squeeze as many as it can in that's a power of adaptive layouts we don't say how many columns they are we just say how big they must be minimum and maximum and it will do the rest for us if you wanted to have more control over your column layout you can instead use something like flexible layout now flexible or have is one of these will mean take up all available space with each cell what happen when I run back with one column is it'll get a single column all the way down so each item is now spreading out to fill the entire row it's on however you could say I want two flexible columns and now if you do that you'll get two columns subdividing the space between themselves like that so they're dividing in this middle somewhere and go further you want to have let's do 5 columns great it'll subdivide across five columns and work just the same way like that remember I've said exactly five columns here so I go to landscape mode I still get five columns just now there's more room for them there's a third type you can use which is fixed I could say I want to have this one be fixed at exactly a hundred points but a second one I want to be flexible so will happen now is the first columns 100 points wide second column is all the rest of the space let's try that out boom this one sticks to the edge this one expands or label space perhaps in sit in landscape there you go so you can see it takes a all space for this other one on the right here dad so that is V grid's you're not a do hate grid going horizontally and it works really similarly let's try it out here I'll change my data on let's say I wanna scroll from 1 through 10 just like that as a simple range for my items it's not columns anymore I'm gonna do hate grid so I want rows I'll say my rows are only one had to be fixed at exactly 200 points then for our scroll view this thing now must be a horizontal scroll for you they're vertical by default now it's horizontal I don't want to have AV grid I want a hate grid and that will take Rose rose I remove the spacing cuz another point when I have one of these things I'll say instead we have alignment of dot Center and then we will loop over our data bring each one in and for a text I replace that with a text of heading items' like that and remove this padding at the end let's give that a try and see how it looks so you can see now we have our heading taxing across the way but ahead of time I have placed in my asset catalog some pictures called helpfully heading 1 heading 2 down 2 heading 10 you knew planning ahead let's say not text heading want that but image heading that and behold the difference because if height is fixed but the width will just figure it out for us absolutely beautiful so that's grids in iOS 1450 why in iOS 14 swift UI adds a new map view for embedding maps right alongside the rest of our user interface to try it out first import mapkit and now go ahead and define some state which directs the center of the map as well as how much of the area is visible around the map the zoom level so I'll say here at state private var region type this is called MK coordinate region as you can see it takes a center and a span what points center on and how much around it to show now for the center we're going to use a CL location coordinate to D which takes latitude longitude the latitude I'm going to use the City of London which is 50 1.50 7 - 2 - and longitude I'm gonna use - Noor point 1 - 7 5 that is roughly the City of London now for span how much you are to see I'll do an MK coordinates pan with lat Delta and long Delta of not 0.5 and not 0.5 the measure in degrees and with that that is our region defined we can now put in our main body area a map with the coordinate region of that region that's all it takes when I press command R now you should get a fully interactive map from drag around pinch and zoom and more so it's thinking there we go there's London I can alt option drag to zoom in/out and then move around like that and this is a binding behind-the-scenes this is why it's dollar reaching you're not just region which means as you move around it will update the region with the new center point and a new span you in iOS 14 swifty wise tabview gains a new superpower the ability to pace through multiple screens of content just by swiping through let's try it out here here's a very basic content view with hello world I'll leave that alone and go across to my main swift file with the app main thing is here with your window group is you see I have content already here I'm gonna add several content views and wrap them all up inside a tab view put them all inside there and now to activate the new behavior we're going to do tab view style and give it a style page tab view style and that's it now by default you're gonna see paging dots that are white on a white background they're very hard to see you can either customize this to make them clearer you could say something like um dot index view style page index view style with background display mode dot always for example so it's always a nice background behind them or give your views a background color here's how it looks right now with a simple page tab where the dots always visible as hello world here's our paging doctor because here's one here's white on a very light gray I can swipe through like that awesome mitten really stand out make your views dark you know go to your content you up here and then make your text have a frame with a max width of dot infinity and a max height of dot infinity and a background of color black it'll stand out much better against that background or being well boom there we go and our paging content looking really nice in iOS 14 swift UI gains the ability to put sprite kit views directly into your view hierarchies at full speed with physics and more let's try it out with some real code first things first make sure you import sprite kit that being the most important part of this whole thing second define your game scene I'll make a really simple game scene here just we can see it all working with physics and so forth I'll say class game scene inherits from SK scene I did move to view method here and in there I'll make a physics body for our world equal to SK physics body using the edge loop from initializer with its frame then I'll make a touches began method and when first thing in here now says guard let touch equals touch equals touches dot first else return so attempt to read the first touch on the screen then we'll find where they touched in the scene by doing let location equals touch that location in self at this point we're going to create a new box where they touched and here are some physics so I'll say let box equals a new SK sprite note using the color size initializer the color I'll say dot red and the size I'll say CG size with a width of 50 and a height of 50 like that now I'll say to this thing you are positioned at the location where they taps and you have a physics body equal to SK physics body using the rectangle orb initializer down here to again CG size with 50 height 50 I finally add that child to our game scene that's the entire Swift sprite kiss scene I'm gonna add here obviously you have your own game with more advanced stuff in there that's enough for a test out and now in our content view we want to show that somehow it's really important when putting sprang kick content into swift UI that you give the sprite kit scene a size if you loading this thing from an SKS file you'll get sized automatically because it's baked into the SKS file here doing it programmatically I've got to give sighs by hand I'll do that with a computed property in mice content view struct here I'll save our scene is an SK scene and do let scene is a new game scene seems size is and how to use CG size width of 300 height of 400 I'll also ask the scene that your scale mode equal to dot fill so we'll resize correctly and then return that scene back to be used and now finally in our body for our content view we can use a sprite view we can say two sprite kit I want to have your scene load into here into this swift UI view with a particular size and so forth so let's say I want a sprite view here using that scene I just talked about with a frame width of 300 height of 400 that press command R to run that back in a simulator now again this uses sprite kitten natively so you get super fast graphics physics and more here we go I press down comes the box I'll add some more down come lots of boxes all with physics and more in iOS 14 swift UI gives us a color picker for letting users choose a color on the device while the app runs to try it out making new property which is at state I'll use private VAR BG color and make it equal to color white by default and now in your body make color picker I'll do color picker UI label being set the background color I have a selection what abided - I'll do dollar bgcolor okay if you want to give this thing a frame for example it might say exact height of 200 that's when that back and see how it looks so as you can see there's my prompt set a background color and our color picker area when I press that we'll get this rich UI pop which says we're going to choose colors from here change your pasty stalker as we'd like but a spectrum view we can drag around or your new sliders that mix colors exactly as we want awesome by default swift eyh stack and V stack both load their content immediately when they're created which is likely to be slow when you make views upfront in long scroll views as of iOS 14 we now have lazy versions of both those stacks which load their content on demand it's much more efficient for lots of data let's try it out here we can say in our body I want to have a scroll view and inside that have a lazy V stack a lazy loading V stack I'll do a for each one through a thousand using ID back slash self and the value coming in and I will do text row backslash value down through interpolation and boom you'll now get a lazy loaded V stack now they are subtly different from regular V stacks and you might just see why if I scroll around here let's load of them as we go but look at the scroll bar here on the right edge of my phone area I can click and drag in this white space to scroll around now let's make that not lazy a regular old-school V stack like that and you'll see a difference in the size here look at the scroll view it's now right next to the edge not on the edge of the phone and interaction options so if I click on this white area nothing happens anymore and what dragged directly on the text this is because the lazy versions of V stack and hate stack automatically have a full area preferred width and height will expand to fill the space which makes sense because they're lazy doesn't know how much content it's gonna need so take all available content now when using these things you're gonna find that little lazy loaded stuff which is great once it's made destruct it'll keep it in RAM the view struct and you can see it in action if we were to have a test row up here struct sample row conforms to view if I do let ID isn't int and then for our body you and text row ID so I'll have a text the ID in the row and in initialize they'll have ID int now print out that we are loading row ID so we can see what's happening assign that to our own ID property and now in our for each down here we can say for each one through a thousand and let's pass that directly the content sample Rho dot in it so make the sample wrote now up front and we do that it'll print out loading row one loading row two and so forth let's find out so if I bring us up here it's a bit of space you can see it's loading all the rows all the rows up front because we Slav are simple old-school v stack lots of rows being made by change to a lazy V stack and do exactly the same thing now command R we should see only some rows being made down at 42 or so yep down there there's no more after that at all of them I scroll you'll see more get made automatically right at the bottom let's made them all they will stop making them it'll keep them in RAM if I scroll back you'll see no more messages being printed out because that view struct once made stays in memory in iOS 14 swift you eyes got a new progress view for showing progress for given tasks on the screen this might be determinant ie a progress bar going up the way or indeterminate a spinning activity indicator let's try it out now in a simple spinner you just say progress for you nothing else and just doing that one simple thing you'll get a spinning activity indicator like that one you want a label you can do so I'll say downloading I'm making that change will now say a spinner plus downloading slightly more information more advanced usages ie actual bar going up the way your ass start by saying what state determines the value of that bar I'll do at state private VAR download amount equals no point naught I've downloaded nothing right now and I progress for you I have downloading attach my value to the value property and I always want to say what's this out of is it 0 to 1 0 to 10 zero to a thousand but down to you here I say total is 100 I mean if this download amount is between 0 and 100 and now we can increment that your V stack here I can add below the progress view a button increment download the action download amount plus equals 10 every time it's pressed increment download amount by 10 10 10 and so forth so if you're on that code back we should be able to make our bar go up by pressing the button so up up up all the way up like that now be careful if you're beyond the total you'll start seeing errors like this one here being very angry so you don't want to do that otherwise f50 why shouting at you do not go beyond the total otherwise get warnings and the logs and so forth clamp your value with some sensible code example you might say you know if download amount is less than a hundred do that otherwise don't do it otherwise you'll get errors everywhere in iOS 14 swift UI has a new native video player component for playing videos that are remote all local to get started add an import for AV kit where the new video player lives and now go ahead and use a video player view you just do a video player and give this thing a player to work with so you'll do a V player which wants a URL and it could use bundle main door URL for resource here if you want to or do a remote URL reside like I'd say URL using the string HTTP colon slash slash bit dot Lee /sw swift a talker game about Star Wars in Swift and I will force her up that's I know it's safe and I'll play the video back and I should say in the current simulator beta that will not do anything it'll freeze the app won't do anything at all run on a real device and you'll get a beautiful playing movie now if you want to go take it a step further because you can pass a second proud of a video player that adds a watermark on top of the video it's really easy to do all you do is say open brace and provide some content you might say I want a text watermark using the font dot caption with a foreground color of white and a background color of color black that are pasty not 0.7 and a clip shape of capsule like that and I'll even wrap that inside of V stack and add a spacer at the bottom so push it to the very top of my video view in iOS 14 swift UI has a new view type called label it shows an icon add some text side-by-side let's try it out now we say the label with some text I'll write your account then either a system image from SF symbols or your own image I'll do system image this I'll do person crop circle now right now in the current beta this is quite broken as you can see the alignment is way way off we fix soon hopefully the next seed will find out soon but when it works correctly the icon and the text will scale together correctly with dynamic type making it much more flexible if you have your own image just put in here just say image your image like that instead now if you want to you can customize this freely you could say I want to have Matt system image but I want to have it in dot font but title I'm gonna do that now you'll see it aligned miss badly and a bigger font like I say it will be fixed later on all being well if you want to you can even provide custom content to have your own layouts for the text and the image so you might say for example I want to have a label inside their text Paul Hudson and I'll do dot foreground color secondary dot font large title and then some padding on all edges it's fine then a background color let's do a color grey dot opacity not point to and clip that to a capsule and then for the icon I'm gonna say our a rounded rectangle or the corner radius of 10 points staff appears is fine and I'll fill that in with colored up blue and give that a frame with a width of 64 height of 64 like that boom really nice in iOS 14 swift UI gains a new link view for making tabble web links that launch Safari let's try it out here I replace my text hello world with a link saying learn Swift UI I have a destination this takes URL URL even so I'll do the string of HTTP colon slash slash dub dub dub dot hacking with Swift comm slash 100 slash Swift UI and force unwrap that and that's our link button right there I'll be visible as an interactive blue button by default obviously capable and when that's pressed it will go ahead and launch Safari with that URL there we go it meant to get there but beta1 who knows so you can see link working really nicely now this thing's just text so if you wanted to customize it you could say I want to have dot font but title dot foreground color don't read customize it however you want to but I have now a red large title boom learn to do I if you really want to you actually customize it entirely you could say instead of having the text here go straight for the destination and then athelets nation do an opening brace and provide custom contents for your link you might say I want to have an image with the system name of link dot circle dot fill and put that in font large title and now I'll get a link picture which is exactly the same thing before but a nice large button in iOS 14 swift UI gains a new graphical datepicker style for doing much more advanced and beautiful date selection and time selection let's try it out here first you want some state to store your date I'll do at state private var date equals the current date and time and then in our body we'll do a V stack then text enter enter even your birthday with font large title and below that a date picker I'll do again enter your birthday for screenreader purposes selection date dot date picker style the new graphical date picker style and then do dot frame max height of 400 and I'll add also here dot labels hidden because the labels above it up here boom and I think that tri-c out looks fantastic it looks absolutely gorgeous quite frankly you need to swipe through and select dates and times and so forth it looks much much better than the old style it's spinning wheel as well if you want to it's amazing in iOS 14 swift you I gained a new disclosure group which shows a disclosure indicator that when pressed rolls out to show some charred content below it but otherwise hidden let's give a try some code in its simplest form you just say that a disclosure group with some content our to say show terms the title and our content will be the text of long terms and conditions here repeated many many times so let's do long terms like this boom there it is and add a little bit of padding around it make it be easy to see actually around the disclosure group sorry and then when these things fold out they work better when they're pushed to one side so I wrapped the whole thing inside AV stack that and add a spacer below this loader grid so go to the top and here's how it looks on out of the box impressive net that out falter content now one thing you can do here if you want to is to bind that to a property to show and hide things programmatically so I could say instead I want at state private var reveal details reveal details even equals false and bind that to our disclosure group I can say is expanded bound to dollar reveal details so now I can control whether it's showing or hiding its content based on toggling that boolean otherwise having changes so fast look that's sure that the same so here's our think still but now but a boolean I can control that I can say inside this group there is a button saying hide again which will have the action of reveal details dock toggle so hide the thing from inside itself that's without right I can fold out here and hide it again from here it's down to you in iOS 14 swift UI views now can have toolbar items above or below them in any navigation view let's try it out here I've got text hello world padding already I'll wrap that in a navigation view like this and I'll add a simple modifier keypad navigation title I'll do Swift UI and now I'll add a toolbar item here I'll say dot toolbar and it'll prevent a pretty pre-made toolbar item for me I'll modify just slightly to say this thing has a placement of dot bottom bar go on the bottom bar my content will be a button saying let's do press me and a content where it's pressed of print pressed that you see there's our button working nicely now if you want to have more than one button inside the toolbar you can do that by having a H stack inside your toolbar item so I'll just say H stack here push my button inside there and make a second button I say button second boom and now I have to toolbar items now this placement enum here is very very powerful because you can add top bar items as well you can see nav bar leading and trailing left and right and lesser I'd languages but also thing is like destructive action and confirmation action or cancellation action to have built-in behaviors that work well across other platforms too in particular things like principal will look great on iPad because they're aligned to the center area so you have actual items direct in the main area of the screen really easy to see and really used to work with in iOS 14 swifty whitelist gains of new initializer to make expanding groups of content you have parents whether disclosure indicator that pops down to reveal children inside it let's try that with some code first define your data I'll say I have a bookmark struct that conforms to the identifiable protocol I'll make sure these things have an ID or just a UUID each time after each bookmark has a name string and an icon string and inside it for the children an items array of type bookmark optional now be careful here the type of your struct in this case bookmark must be the same type used for its children so a child and the parent have the same type now you want to go ahead and pull in your stuff from disk or from Jason whatever you want to pull in a load of bookmarks using codable presumably I am NOT gonna do that here it's quite distracting instead I have pre-made some example bookmarks down here I'll uncomment you can see that I have a Apple BBC Swift and Twitter as my bookmarks and there are some groups here favorites recent and recommended and each one I've put the same bookmarks Apple BBC Swift and Twitter just bit of code easy to follow along ok now let's go ahead and use that first things first you want to in your content view give your array a name as a property where you want loop over so I'll say my items my parent items is going to be bookmark array but marked array equal to dot example1 example2 and dot example 3 so those are my example bookmark groups I made in my hard coded array below and now inside your body you can make a list of those items just like before except now you also say the children of those are backslash items and are pointing to this items property inside our struct we're saying that Swale find the children for each item and now you provide your regular role function what code should be run for each row you want to demonstrate so I'll do image system name of road or icon and text row dot name like that and we'll get by default out of the box this kind of disclosure indicator approach here I'll run the code and as soon as you can see how it looks for real your exclosure indicators out of the box and when you press them you'll see two slides out the children really really slickly like that fantastic in iPad OS 14 Swift you I can now show sidebars for iPads let's look at how it's done in some code first define your views I'll say the struct called sidebar that conforms to view as bar body returns some view how does do text sidebar so we can see it's there I'll then copy that and say this our primary view this would usually be on the left hand side and list your something like that I'll say primary and then a third one this would be our detailed view so I'll do detail in here so you have three views now sidebar primary and detail and now in our content view we can start using those to build an iPad OS sidebar I'll say and here we have a navigation view go to our sidebar first then our prime review and now also our detail view I press command R to build and run that using the iPad pro 4th gen simulator and here's primary here's detail and now this button appears automatically I can press that to bring in or hide the sidebar it's really really nice so I switched to Y as you can see if they can care of showing that button for us bring it in and out for us automatically if we had multiple apps open say we had Safari over here it would take care of collapsing them down for us with less space now that one comes in it's now a navigation view over here like that automatically collapsing it all down for us now if you know you do side bars with a list I recommend you customize this very carefully let's try it out first if I go back to my sidebar and say that is a list of one to a hundred with I coming in and text I'll do row I boom I put a list here now when you have lists in your sidebar you should really use dot list style sidebar lists of style you get a system standard sidebar look and feel let's see how that looks on the iPad so our two main views are affected but now sidebar comes in this new gray look and feel to match the systems that I'd look for iPad or Westside bars Swift ey comes with support for document based apps built right in which makes it really easy to create edit and share documents using a system standard user interface let's try it out here the first thing I want to do is define what kind of data you're working with we'll start by importing a new framework called uniform type identifiers this contains a massive long list of these UTIs and describe things like movies audio pictures text files and more then we'll say the data we're working with is a struct called text file plain old text but it must conform to a new protocol called file document it's capable of loading and saving files now to conform to this protocol you've got to start by telling iOS what kind of files you want to work with is it pictures is it movies and so forth so we're gonna say static var readable content types now make this be an array of U T type dot and there are many of these things in here you can scroll through and admire them all you'll see things like his movies mpeg-4 movie there is Perl scripts ping Python scripts even swift sauce and more listen slow I'm going to say plain text plain old text great file format so that's what we want to open and save the system knows what kind of files we can load next up we want some actual text to work with so I'll do via text equals an empty string by default there's nothing in there I'll make an initializer called init with initial text be a string equal to an empty string and assign that to be to our initial text so you now make new documents with text you want to have now below this we have to have some more methods to conform to that file document protocol one is in it with file wrapper so far wrapper is a file stored somewhere on disk we don't care where it might be iCloud for all we actually care point is this thing will have the files contents as our job to read it out as data and convert it to be a string and assign that to our text property so I'll say if let data equals file wrapper dot regular file contents if we can read the file wrappers contents brilliant we'll assign the text the string decoding that data as utf-8 dot cells so convert the site save file data to be our text string the second method is the opposite it's called right to file wrapper this is when it's time to save our text string to disk so in here I'll first convert our text to data by doing that data equals data text utf-8 then say make a new file wrapper here using the regular file with content initializer what you want to put into your file the answer is our data now this works because we're handed this in out file wrapper we can do with that whatever we want we're making a new one with our content and sending it back I'm not saying where to save it won't give it a file name it's down to the system to put it in the right place very very nice so that's done that's our file format right there the next step is to build our editing user interface and it's been really simple down here not content view I want to say there is a document coming in a text editor editing in that document so I say binding via document is a text file now it's up binding here because it's me passed in externally but we don't own it want to modify the external version so it's not our copy so our text file which is referring to an external file passed in from somewhere else as I document right there and now we can say in our body there's a text editor with a text being bound to dollar document text so as we change the text editor it'll change the external text file and now our final step is to go ahead and edit the main Swift file for this project and up here is your at main file this thing has a window group by default rather it's change out to be a document group which is responsible for making new documents this wants to know how to make a new document I'll do the document is a text file and it's gonna pass in the file that was made so I've made you document what you want to do the answer is file in bring it in and for our content view do document file dollar document so it'll load that document into our content view remember that's at binding or changing the remote one not a local one so update the clouds of appropriately now as you can see when you make a Content if you like this we got to pass in the document to work with which also means if you want to use 50 wise previews down here you've got a pass one in here as well for testing purposes you might want to say document is dot constant text file that's fine to just somebody's already passed in there they press command R now we should get a nice document based app ready to go let's find out boom his recent and his brows I can press plus make a new document there it is and I can write in here hello world this is Swift UI text based document editing in action boom and that will be saved I press back it'll go out see a little preview here my text they flushed out to iCloud and backed up automatically in iOS 14 swifty wire gets a powerful new modifier called matched geometry effect lets you synchronize view animations from one view to another almost like a magic move in keynote let's see how it works in my struct I'll make some state at state private var is flipped is false and in our body I'm going to find our view state so I'll say it as a V stack and if is flipped is true I want to have a circle with a fill of color top red and not a style I saw on color red and a frame width of 44 and a height of 44 and below that some text I'll do Taylor Swift 1989 in dot font dot headline and then I'll say else and paste in that text below language so the text comes first and a circle comes second and now if I just scroll down a little bit I'm going to add a modifier to the V stack to do on tap gesture with animation self dot is flipped toggle this is fairly old iOS 13 style code or you see how it looks if I do animation correctly there we go see how it looks with iOS 13 code first and then we'll apply a match geometry effect there is our title and our circle when I press on them they'll flip like that it'll fade out and fade in again that's the default Swift UI animation it kind of works but in iOS 14 that we can do better because we'd actually tell IRS that this text and this text are the same and this circle and this circle are the same as we animated together as one and it's done in a few steps first you make a namespace at namespace private VAR animation I'll call it it's just a placeholder where 50y can store views in and the global namespace to say yeah this one in this one they're the same it's always going to be doing and then we're going to say for our circle this first one dot match geometry effect the ID can be animate like numbers or strings I'm gonna use shape in a space that only made animation are the same one to the other circle so the same matched geometry effect same ID shape and shape in the same main space animation both times and for the text I'll do another one math shown tree effect ID I'll do album title also in the animation namespace I apply that to the other text as well so that both markup in exactly the same way let's press command R now see how that looks when I press in it they move smoothly now it's correctly animates them from A to B it recognizes the same view so animates them correctly it's much much nicer let's try a more advanced example let's uh get rid of some code here again from scratch I'm going to go ahead and keep the animation namespace so that's exactly the same the state I'll change to is zoomed equals false then our body here we can use AV stack with a spacer atop pushes all our stuff to the bottom and then inside the least after that'll do another V stack and a haystack and I'll make a rounded rectangle with corner radius 10 like that filled in with color blue with a frame now for the frame here I want this frame to change size depending on whether it is true or false so I'll make a computed property for that var frame your CG float and it return is zoomed question mark 300 otherwise 44 so our frame now I can say the width is frame the height is frame then we'll do padding-top and the amount of padding I'll do if we're zoomed I will do 20 otherwise zero then after the rounded rectangle and add some more views and I say if zoomed is equal to is zoom sorry is equal to false then add our text Taylor Swift's 1989 and I attached to that the match geometry effect again I'll use album title in namespace animation nation and give us a font headline against a beginner screen and give it afterwards a small spacer so it's pushed to the side of the haystack so that is our is zoomed then after the haystack down here I'm going to add if is zoomed is true then the same text again so that is text Taylor Swift - 1989 89 even dot font dot headline and Matt Shana tree effect ID was album title in animation I also add that there padding so it was nice when a screen let's just do bottom let's do 60 points of padding there and again add a bit of space there below it like that and we want to say underneath let's get this right here cuz quite a few things now underneath this V stack here we're gonna add and on tap gesture this one just here will do on tap gesture and with animation I'll do a spring this time slightly different style animation even we'll know we'll do self dot is zoomed toggle and I also want to say to the V stack actually a you have some padding around you and a frame with a max width of infinity and frame height is gonna be is zoomed then 400 otherwise 60 and background-color:white nor point 9 sure lots of code in there did he get all right let's find out slightly more advanced effect all being well there is our title test with 89 by pressing it it'll fold out like that so kind of rips off the Apple music now playing area but it'll fold out tray at the bottom so what's happening here is we have a text here inside a haystack as you're seeing here hey Chuck has a rounded rect this thing a text next to it but this text here is only showing when is zoomed is false so when that becomes true this text no longer shows instead this text shows this is outside the haystack in the parent V stack so it shows below the rounded rect so lets the toggling one text for another text this one for this one and in doing so because they have the same match geometry effect so if you want to animate them correctly between those two positions we also have a frame of our rounded rect being modified that's a little mock album title so it's all animating very very smoothly just do this math geometry effect modifier in iOS 14 Swift UI gains and new ability to be able to scroll down in a scroll view to a particular location to show of you let's try it out now first we'll make an array of colors we can show in various shapes on our screen I'll say let colors be a color array equal to the colors red then green then da blue then our body I'll say as a scrollview and then our new type here which is scroll view of reader this works just like jollity reader you can put code inside there I'll pass you some data a proxy in here which you can refer to so I'll do value in and I'll let us refer to things inside there for scrolling purposes so I'll say button jump to number eight and side there I'll do value dot scroll to 8 so we'll scroll to the view with identify eight and now below that I'll do for each zero to ten doing I in text example I'll use for interpolation I so you can see what's happening I was a fixed frame with a width of 300 and a height of 300 so we can see clearly where it is for the background using our colors array and I modulo colors count and then I D I so as the gente fire 0 up to 10 let's refer to each view uniquely in there and now I press come out our to build and run that code we can press a button which will cause scroll to number 8 here's our simple rectangles a fresh jump number 8 boom no bail appears and I'll take the laziest root by default you can see it's scroll so enumerates just about visible the bottom of the screen if you wants to control that you can actually pass the second parameter to scroll that scroll to you can say scroll to 8 Anka is dot top or dot Center scroll to a particular place on the screen while showing number 8 let's try again with Center and our pressed ROM to number 8 boom smack in the center like that i OS 14 has a new swift UI modifier called full-screen cover it's a presentation style that takes up as much the screen as possible let's try it out here I'll start by saying some state determines where the screens being covered or not I'll do at state private var is presented equals false then our text area here I'll do button present language action self dot is presented dot toggle and now I'll attach the full screen cover I'll do is presented content it's presented we bound to our is printed binding and then for its content I will provide in here a full screen modal view of some sort I'll just do a full screen modal view like that in fact in this case it even just do is presented and then do content that dot in it even even less code which is good now obviously this thing full screen modal view is not build stuff to you I go to provide that thing yourself you might have something like this to get started struct full screen modal view controller call I have at environment back slash dot presentation mode so we can dismiss ourselves bar presentation mode then var body returns some view and site here I'll have simply a V stack with text this is a modal view text have to dismiss I'll do frame has max width of dot infinity max height of dot infinity dot background let's do color dot red edge you don't safe area dot all and on tap gesture I'm gonna do presentation mode don't rap value not dismiss to hide itself let's run that code now and see how it looks so their present button and I presented the full screen cover kicks in as you can see the whole screen is now hidden i press this it'll be dismissed in iOS 14 swift UI has new superpowers to handle date formatting right inside text views let's try some of them out now I could say I want to see a text where it's date through to another date though adding time interval 600 by east 600 seconds and that'll render as 8:35 - 8:45 p.m. so 10 minutes range rendered right there easily can also format dates neatly we'd say text date dot adding time interval 600 using the style of date showing just a date for that jun 23 2014 for that 8:45 p.m. wearing it's really clever if you ask for relative times and you'll see 9 min 59 sec now I press command R to run that code in the simulator watch what happens here boom it is counting down for me from a time I started at to ten minutes later like that that's relative time and he even go further you could say actually I want to have a regular timer get a proper full-on timer now and as for method like a timer a countdown timer so benign : 58 57 56 and so forth and the amazing thing here is that it's changing live but swift UI is not reinforced from a swift DUI teen said this is basically like an animation so if do I understand I'm going from this value to this value over some time it's not reinventing body property so it's lightning fast to do this kind of thing i OS 14 a small but important change for swift UI we can now use the iOS 13 inset grouped table style let's try it out now I'll say I want a list that loops from 0 up to a hundred I'll do I in and then text now let's do row I and then for those list style because we can now say I want to use a new insect grouped list style like that and it's gorgeous it's really nice and finally it's available to us inside Swift you I like that hmm yeah it's good in iOS 14 swift UI gains a new unchanged modifier that can be triggered when some state changes let's try it out now I'm going to say I have some state here at state private var name is an empty string I'll use that in my body by saying text field with a placeholder enter your name buying the text of that two dollar name like that now it's nice and clear with a text field style of rounded border text field style but when someone types in there I want to run some code so I'll say dot on change of name give me the new value in I'll just do print name change to back slash straight to ablation name like that this means is every time name has changed it'll print out a message into the log I'll type in here my name is obviously Taylor Swift and you can see it's pretty down here Taylor Swift as I'm typing in iOS 14 Swift ey gains a new App Store overlay modifier which lets you recommend App Store apps by sliding in a banner from the bottom blender tap on now you could recommend anything here and it's good for things like if you like this app you like that app to to cross our customers but Apple are also recommending it for the new app clips we can slide in a link to the full app let's give a try here first you mark some state that will track whether the overlay is currently showing so I'll do at state private var show recommended equals false so it's not showing by default then our body I'll make a button saying show recommended app how do you show recommended toggle boom and then I attach to the button the new app store overlay modify it so once we bound to it is printed boolean so I'll do sure recommended and I'm clicking figuration I'm going to pass back a new instance of SK overlay dot app configuration now the SK here means this thing comes from stork it sort of import stalk it into here import stork it and now all being well should get Co completion boom asking you where you want to slide it in from and which app you want to recommend I'm a link to my own app which is 1 4 4 0 6 1 1 3 7 2 and position where come from I'll do dot bottom now this doesn't actually work in the simulator and write it back you'll you'll see something but it's not the full final product let us see a test banner instead you'll see that App Store develop a preview so you can see that it's work correctly and obviously in the real app on a real device it'll show the actual App Store link right there in iOS 14 sf symbols now comes of multicolor varieties for many pictures and it works great in swift UI out-of-the-box let's try it out here and let's say I have an image with the system name of cloud Sun bolt dot fill let's make it easy to see I'm gonna add a font of large title then add some padding then add a background of color black and then a clip shape of circle so that's on your picture and you can see it as a stand out very well because it was black and it's now got black behind it but if we ask for a multicolor optional sf symbols it'll really come to life and in Swift ey you just say dot rendering mode dot original and you'll get their new colored version in iOS 14 swift UI has a new export files action that lets a save files from our app to anywhere else user can write to for example iCloud or a folder in their files let's give it a try encode a pyramid property at environment and I'll use backslash export files as the key VAR export action and this thing here becomes a callable function we can use to export files to the system it's a really really easy way of working down here I'll use it I'll say as a button which is called export file and when that's pressed we will load a URL from somewhere and call export action with it now the file you use has to be moveable I'm gonna cheat here and use one in my bundle cuz it's easier but in your own code it'll be the documents directory or the caches directory or somewhere else like that that you couldn't move freely otherwise it will fail so my URL is going to be bundle dot main thought URL for resource I've got symbols dot Jason already prepared in my folder up here but again this won't work in practice because you've got to be able to move the file and you cannot move things from your bundle now for some wrap it because I know it's safe but also if it's a live demo there are some shortcuts we can then call our export action passing in that URL for moving I'll be moving that URL and it'll passes back a result and results going to be a URL of where it's been move to or an error of when wrong or nil the user canceled the whole operation let's give a try now I'll do switch result case success let URL if it's worked we'll say print success moves to URL then we'll do case failure went wrong let error print oops and then error dot localized description and finally remember it can be nil the user cancel the operation so I'll do case none print cancelled and that's it that handles all the possible cases for our type like that so let's run the code back you can see how it looks remember it cannot actually work in practice because I'm trying to move something from the bundle but Li see the Yurok UI as export file boom up pops iCloud drive or on my iPhone then you rename the file here and so forth and it can on a real device that can browse through all their folders and choose an exact one it's a really really nice in iOS 14 swift UI gains a new modifier for text fields to control the text case shoot uppercase or lowercase or natural we can do in here let's do at state private VAR name equals poor then our body and what to write a text field with the placeholder shout your name at me with text dollar name and we'll do text field style a rounded border text field style so we can see it then the new text case modifier I'm going to use here dot uppercase and she was the default but it was filled in mother yet editor and then dot padding I'm going to use dot horizontal like that and now it's going to force me to write my name in uppercase so I'll go into here and write my name I'll write an instead of Taylor cuz pause there ready of course it was there we go Taylor because hit uppercase regardless madam what you type here edit all uppercase in iOS 14 swifty wise got a new app app storage property wrapper for reading and writing values with user defaults let's try it out here and I say at app storage then give a key name under user name' VAR username is anonymous then our body I'll make a V stack with text saying welcome username and below that we'll have button saying login and when that's pressed will lose itself or just username sorry equals at two straws like that read rifle to be Hugh straws when it's pressed and when that's codes run it will show anonymous by default when logins pressed it'll become two straws and what's happening behind the scenes here is were changing the property from anonymous to two straws of course we are it's what the code is doing but we're using at app storage which means when I real aunch the app it will show two straws hopefully let's find out boom two straws so it has correctly save the manager user defaults and read it back in again and the best bit is this will also work if any other part of your code also writes to user defaults so you had somewhere else anywhere else in your app user defaults dot standard dot set at two straws for key username that would still be detected by a tour app storage and Riaan VOC the body property to show our new user username now we can do if you want to is add a second parameter to the app app storage property wrapper you can say the store where to read values from by default it is user default start standard but you could also say I want user defaults sweet name group.com dot hacking was swift dot example whatever you want to have a custom user default sweet name to read them right from in iOS 14 swift uija gains a new scaled metric property wrapper to scale that is up or down according to Derek type let's try it out here I'm going to say at scaled metric var image size CG float equals a hundred and our text area replaced that with image system named cloud Sun bolt dot fill I'll make it resizable and resizable with no extra parameters and have a frame with a width of that image size a height of that image size like that so it's going to scale up or down according to the dalek type settings we have for our app my press command R now to build them on our code you should see the app run there we go and if I put this to one side over here I can grab this little thing down here to control the then I type and see how the text to be extra large like that I'm gonna go back to simulator you'll see the Emma is really really big sort of scale completely correctly with the font size changing like that in iOS 4 swift UI has a new property rapper called scene storage this lets you save away small amount of data attached to individual scenes inside yo user interface it works a bit like app storage except rather than writing to user defaults this is used for state restoration which is amazingly important for those complex multi-window iPad OS environments that are increasingly common today let's try it out here I'm gonna make it my content view a new property using at scene storage I'm give it a name for a key to be serialized out with I'll you saved I'll do var text equals an empty string that's a value want to work with that we read and written to the scene restoration API in my body I'll make a navigation view I'll place the text editor inside there with the text bound to my text state angles were an iPad here and go attach this the navigation view style of stack navigation view style just to make it easier to work with I'll make the whole screen one single text editor let's press command R and give it a try that's all the code we need so it's lowered my simple text editor a good impression to hear and start typing I'll do hello world but this is an iPad so I can go down to the dock up here swipe upwards and bring in another copy of my application down to the side over here I'll write in this one goodbye world and that's it it'll save my stuff for me I can go away run other apps come back later on in this case I'm going over go ahead and kill the app from Xcode and then relaunch it to simulate the user coming back later on and you'll see both sides of my application come back correctly both scenes have their own unique storage and remember that over time in iOS 14 swifty wire gains a new property rapper called at state object let's try it out here if I say in a new class called user that conforms to observable object I might say as one property values a name which is at two straws by default now to use that inside content view prior to iOS 14 you'd have written code like this at observed object VAR user equals a new user and here in the body you'd have written code like this text user name colon string interpolation user dot user name like that and most of the time that would work that would work great sometimes that code would crash and the problem is that Swift UI is free to destroy and recreate its views whenever it wants to because they're structs they're extremely fast to create that's the point of them and so maybe if you're four levels deep in a navigation view it goes huh it's things old only that anymore it'll toss it away and then recreate it later on what would happen is if that happened to your view this user would also be destroyed and you'd lose that object and also it's a case that sometimes this body property could start being run before the years even been made so it's caused problems and it caused your code to crash completely randomly then work just fine otherwise and so they've made a new property wrapper at state object like that that's the only change to use it it's really really simple but now Swift UI guarantees that user will be made before the body property runs and it will exist even if the views been destroyed and recreated it will always exist which is really really nice that it's being guaranteed safe and correct now the way to remember this is quite simple when you say at state or at state object the word State is in there it is owned by your local view everything else observable object observed up to even environment binding and so forth is owned somewhere else so at state owned by you that's an object owned by you and if I'm creating it here inside my content view and then of course inject it into the environment or pass it in to somewhere else a property I'm initializing it that also works if you're creating it first you want to create it with at site object it's also applies if you're using a new main file over here you need at state object here to create your data once and pass into your content views from here in iOS 14 swifty wise app lifecycle system has been dramatically simplified I press command 1 to reel a navigator you can see app delegate gone seen delegate gone instead we have a single file named after your project where the at main lives that's what starts your program off and in C is a struct here with your apps project name that conform to the app protocol and that's how it starts with app these days and this means two things first you can change your initial view right here you know don't show content view show text hello instead like that right in there if you want to have different views right from there and second if you have some app wide data you want to create and inject into your first view directly or using the environment you'd make it here in this app struct so you'd say something like at state object VAR my data equals a my data object like that and pass that into the environment right from here in iOS 14 swift UI apps become much much simpler in the way they launch but sometimes you want to go back to the old app delegate style approach to catch things like push notifications and similar you can do that now by going to your app file where your ever your app main scene is and customizing it here first you want to have some sort of class to act as your app delegate just like you would have had previously so I'll say as a class called app delegate inherits from nsobject and could forms the UI application delegate protocol and now inside there go ahead and add any of the standard app delegate callbacks you might want to have for example you might say I want to have did finish launching with options boom I'll do print finish launching and then do return true just like you don't had previously so that creates a class you want to work with and now we can attach that to Swift ey we can tell it up here in our main app struct that is a UI application delegate adapter and give this thing the name of your class at that look at that self and then the name of our app delegate and that's it this property wrapper here becomes responsible for creating an app delegate managing its lifetime and sending information to it automatically I press command R now we should be able to see finished launching up here there we go boom down here in the console now I would say if you were using did finish launching with options to handle push notifications you should really be using the UN user Notification Center dot current delegate instead it's much nicer way of handling that an external class in iOS 14 swift UI has a new way of handling NS user activity information coming into app for example if your apps launched via a web link or via spotlight or via Siri you'll get an NS user activity if you catch onto and respond to let's give it a try over in our app it's a good place to hand this kind of thing because of course you want to route that somewhere else in your app depending on you know what that user was doing or what the activity was for example you might want to handle spotlight information if you've indexed up and spotlight you want to use it you can do it right here let's give it a try first I'll do import course spotlight office that's what IX I'm doing spotlight but you'll need to be different I'll make a method here called handle spotlight and this needs to accept a user activity which is some kind of NS user activity like this inside here we'll go ahead and read the data you want from your activity wherever your restoration identifier was from in spotlight we're going to say if net ID is the user activity has a user info with the key CS searchable item activity identifier now typecast that to be a string that's what I've stored in my app now I find it out us to print found identify ER ID I'll see that's where you add your custom application logic to show the right screen to route the request to the right place in your app so that's how we handle spotlight and now to attach that to our apps content we go to our content view and we add an on continue user activity modifier and this takes an activity string and a function to call this is really neat because it makes your callbacks really fine-grained you can say here's the string for web URLs here's a string for spotlight and so forth so you don't have multiple of these things with individual functions either once or catch all function like we're done without delegates so here I want to use CS searchable item action type that's the callback name we get from spotlight and when it's performed I'll just do handle spotlight like that so call that method when we're launched by a spotlight have as many of these as you want with different kinds of activity identifiers and they'll all be called appropriately automatically in Xcode 12 some of the most important Swift UI improvements are actually improvements in Swift itself underneath because it's got 12 now ships with Swift 5.3 let's try out those new improvements now first things first if I had some state up here the track of my username and this thing was an optional string I can now inside my body have a group and use if let to unwrap the username I'll do if let username equals username text welcome an entry interpolation username otherwise I'll say as an image of system name question mark circle and give the whole thing dot font dot large title so we can unwrapped optionals directly inside our function builders now with Xcode twelve similarly if we had a regular string here I can have a switch case directly inside our function builder I could say switch username case two straws and I have text off I love your swift UI tutorials then we have case tailor I'll have text I love your awesome songs I think it will have two fault case of text I don't know you like that as here as a default value otherwise we had compile error like this boom and now it'll switch case directly inside our body like that there's one more change is really really beautiful certify so much of our code when we have a button such as this one doing press me previously would have said self dot username equals two straws right there now the self is no longer required in Swift five point three because Swift can see there can be no retain cycles here when a struct we can't have retain cycle it isn't possible and so we can just do username equals two straws it'll work perfectly and that's the end of the video I hope you're inspired by all the new swift UI and swift features it's gonna try them in your own projects iOS 14 is a landmark release of Swift UI bring in so many great features let me know in the comments below which one you are most excited to try in your project and of course you enjoyed the video I guess you did or at the end of it hit like hit subscribe I make many more videos like this one helping you make the most of Swift UI and Swift and so much more you
Info
Channel: Paul Hudson
Views: 36,006
Rating: undefined out of 5
Keywords: swift, ui, swiftui, grid, colorpicker, nsuseractivity, ios, ipados, spritekit, tabview
Id: -h8pk2pe7Xo
Channel Id: undefined
Length: 82min 46sec (4966 seconds)
Published: Thu Jun 25 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.