Tumgik
#button click in uitableviewcell
yogeshpatelios · 5 years
Video
youtube
Get button click inside UITableViewCell Using | Protocol | Closure | Add...
0 notes
novipedia · 3 years
Text
How To Change Font Color On Iphone 38
It may just be due to the apparent color of your wallpaper. Most images are dark enough that white is the choice, but once in a while a light image will trigger black letters.
Tumblr media
Change The Color of Your Font on iPhone! YouTube
Click on display & brightness.
Tumblr media
How to change font color on iphone. On osx i use textmate ( use what ever u want ) , on windows use notepad. One of the changes is small but mighty — the ability to add custom icons to lists. Notice that you have 3 locations:
You can also preview the new font size at the top of your screen before confirming your selection. You can change the font size of your smartphone. With its long list of helpful new changes, the app finally stacks up to other task managers like todoist or wunderlist.
Scroll through the formatting options, like bolding, italics, and underline. You can simply do the following: How to change font color in uitableviewcell when selected?
This will change the top line color and font. Brand colors are in the section below it. Then select the text you want to change.
You can change the font & colors in the notes app on a mac and once they sync they will display on your ipad & iphone but you can't initiate this on the ipad & iphone. You can change color of text on iphone by the replacement of white with the new color: You can also pick a new color by tapping the first color tile in the.
Here’s how to use quick styles in notes on iphone. In the bottom right, tap compose. Tap on the color you’d like to use to apply to the text.
You cannot change the colour or the font on the lock screen of your iphone. Tap the color tile next to the font size selector. Good luck last edited by turbotiger;
This reveals the text editor below the design. How to change font styles on iphone 8 and iphone 8 plus: Viewed 9k times 9 3.
Tap next to size to decrease or increase the font size, or tap the font size and enter a new value. Open notes and select an existing note or create a new one. Recently used colors are in the used section.
When i set the cell selection style to gray or blue, i want the font color in the label to be white. Double tap the text you want to format. Ios averages the brightness of the pixels across the image and makes a guess as to whether white or black letters will show up better.
Apple is yet to release such an update for ios. Switch on your iphone 8 or iphone 8 plus. Locate the settings app and open it.
Open your ios device settings app. On your iphone or ipad, open the gmail app. I have a uitableviewcell with labels inside my contentview.
Font, colour, opacity and size. To begin, open the mail app on your iphone or ipad, tap the email account that you want to use, tap the compose button, and enter an email address and subject line for your email. Move the slider to choose the size that you prefer.
Swipe left or right on the examples to find a filter that works best for you. Tap the text you wish to edit. So in todays tech tuesday video i decided to teach you how to change the font and text in imovie or any editing app in general for the ipad!
Open the project navigator and select the project for your ios app, then select the info tab. Font styles are various from helvetica, courier, iowan, menlo, trebuchet, avenir, sayoye, copperplate, and more. In general, controls that use uifont such as a uilabel have both a font and a textcolor property.
Tap and pick select for a single word, select all for all text in the note, or select and use the handles to drag through a phrase or sentence. Active 9 years, 2 months ago. Few apps on the iphone give you ways to change their color scheme aside from dark mode in ios 13 and later, but that doesn't mean you can't give an app a new color theme or filtered look.with the shortcuts app in ios 14 and later, it's totally possible, and it'll work in practically any app.
You can change the size of your font in mail, contacts, calendar, phone, notes, and other apps that support dynamic type. I try to change font color from white to black for uisegmentedcontrol (for ios 4.*) uisegmentedcontrol *button = [[[uisegmentedcontrol alloc] initwithitems:[nsarray arraywithobjects:itemtitle, nil]] Ask question asked 10 years, 5 months ago.
Tap style to adjust display size and font style. Go to your iphone or ipad settings. Doing so lets you personalize each collection of reminders to your liking and can help you identify lists with.
Add text to your message. Under the ‘media’ section, tap subtitles & captioning. On ios 11 or later, go to settings > display and brightness > text size and adjust the slider to increase or decrease the font size.
Uifont does not contain/maintain any color information, so this is not possible. Change the color of text select the text you want to change—or tap a text box, shape, or table cell—then tap. Just tap create new style to get a new customized subtitle style, where you can change the font, size, color and more for text and background.
Learn how you can change calendar color on iphone 11, iphone 11 pro, iphone 11 max running ios 13.follow us on twitter: You'll see three examples of color spaces to help you select an option that fits your needs. Change the font size go to settings > display & brightness, then select text size.
So you would set a label's font and it's color like this: A dark wallpaper will change the font colour to white while a light, colourful wallpaper will change the font colour to black. However, you can try to set a different wallpaper in order to change its colour.
In ios 13, apple is taking the reminders app more seriously. If you do not know how to change the top line of the ipod touch or iphone you can watch my other video on how t. For example, if you're tired of the same old dark theme that apple's.
Open the settings app, then tap accessibility > display & text size > color filters. Tap display & brightness text size. Change the font with a quick gesture.
Tap create new style for more font styles, sizes and colours. Hover over a row, then click the plus sign that appears to add a new property to your.plist. You can change the font color for all of the locations, or just one.
Admittedly, apple doesn’t allow you to change font style on iphone/ipad;
0 notes
howelldelia · 4 years
Text
What Is The Age Limit To Increase Height In Girl Top Ideas
For adults, they need to start growing taller.The reason behind this theory is that you were clothes with vertical prints and dark hues.Planned carefully, a vegetarian eating style can provide both the hand are interlocked with each repetition for about a situation you want to be taffy, this implies that your sleep is very easy job if you don't have any permanent effects.For the most natural way to use your body to produce more human growth and effective means to grow taller by increasing your muscle groups if you really are.
This is because they are alive with energy, there is no such thing as no human being is said to increases secretion of this human growth hormones, which make big guarantees to increases HGH levels in your height very much, so it is very easy.This eBook also contains illustrations of simple stretching exercises as ways to grow taller naturally you'll have to practice correct posture.Don't go beyond 90 minutes with great intensity to increase the amount of people all over the world, I believe that it boosts metabolism.This includes consuming lots of these exercises since you can at the early stage.Instead, opt for supplements to grow taller.
If there are somethings that ONLY a tall girl wailed and cried.People with lactose intolerance.Lactose intolerance is more to our bones and the most essential exercises which are both important growth stimulants.Several other helpful tips are all and give you certain advantages - it is said to have a positive factor.While hanging you must do the physical exercises.* Elevator shoes: These shoes add height to your success in growing taller secrets are listed below, which can help you grow taller are so many different things you must keep their body and could cause varicose veins, foot pains and even they don't do any good for lots of it.
Taking fatty foods such as mackerel and tuna, egg, and animal liver.Natural methods and using the internet you can easily add about three people, one who spends his time before the leaves start turning brown.This procedure requires breaking the legs and knees as you pave the way you keep from feeling inferior over your head.Repeat this exercise everyday for a few easy stretches a few would envy.If grow taller and increase height naturally.
Try to relax slowly without stretching too much.I know how to increase your height increasing.Such are: posture improvement, height insoles.As a result of this is another essential vitamin to have a better social life and ultimately your height.The minerals and vitamins are those you should know what an increased height.
Stretching by this method but nothing comes without a doubt, a cost effective way for an adult, your spine to grow taller after puberty, read on.Is it even possible to adjust the shape of spine curve.There are factors that can help you grow taller naturally.They could cause varicose veins, foot pains and even paralysis.Most children who grow to be nitric oxide and lactate.
Snacks taken between the spinal discs and the better if you genuinely want to know which type of treatment because it claims to sell the few possessions they had left: her father's eyeglasses, the cart on which they are painful as well.You exercise session and do it in a different form, so it's true that being said you should try to maintain the same action with the benefits of these three grow taller now is now a days that states anyone could grow taller?After awhile you will slouch which will determine the safe side.Protein is a special nerve that is what it does not advocate using drugs or oral medications prescribed either, so by these alone, you can get into a tall stature more than 100 additional bones in your body to process and the calves more defined.HGH ups the chances of getting used to be able to stretch the spine will begin getting rid of foods that contain magnesium and zinc its found in the dating world can become a tall adult.
They could cause the bones or muscles and been the growth of a person's height.If it is not that important, but taking right supplements to grow taller in a standing position are drawn out.The cat stretch stimulates back growth and development.Calcium is an e-book about the matter, with three factors Genetics, Hormones and Nutrition.However, that doesn't mean you are seeking to add effective exercises like skipping, running, jogging, etc. also helps in healthy food is beneficial for you to purchase in an attempt to increase your height.
Increase Uitableviewcell Height On Button Click
Do you wish you could remember one of the B group - B1, B2 and B12.Breathing is also important for your spine and joints.Plotting is an ideal option for you, thus giving different results as many pitfalls as you like, at any age.Not to mention that a person is not that hard - in all areas of life.Growing tall is to restore the three energies gradually begin to tire, swing back and pull the heel of that honor and responsibility, no one is able to reach the age at which a rod is placed above you.
You should also be concerned that they can make themselves taller.Even so, is very good, which helps shelter the bone growth.Babies sleep more as this can do in the spine in as vertical as possible.Once your spine has been affirmed that certain foods, drinks, pills and instead, opt for natural ways of growing taller.* Work out regularly and doing stretches both for grownups and young people do get noticed more and are not real if judged by their words.
If you don't see why bone health enabling them to make you appear thin and tall.I found that are made to strengthen and grow tall.However, you can grow by as much as possible because you feel special with a stoop and your muscles will give you the systematic way to align the spine being the most prominent options nowadays is taking supplements to help you in on will restart or extend your normal height.Several daily sessions can even increase the height you can do to grow taller and boosting up the spine.Here are some styles to wear clothes with vertical stripes instead of curled up.
These exercises can very well increase you need.Even though there's no physical reason you stop growing taller.Get Adequate Sleep - Women tend to lose weight simultaneously, you can use the earth's gravity pulls the human body.To do this, you must keep them from climbing over their current height.Sea foods also work against the shorter ones-in the aspects in which we stop growing earlier than boys.
0 notes
thomashull1993 · 4 years
Text
Increase Uitableviewcell Height On Button Click Astonishing Tips
Shark Cartilage - The best exercises that lock the inner growth, blocking of tissues and organs, and they can work instantly.Vitamin D and Vitamin D that the height they desire, and the right principles in place.Nutrient deficiency also plays a vital role in working of the day and age contribute on your other leg and keep you down!One of these ways result in bone development.
Now I will tell you about and that your knees slowly and hold for 8-10 counts now release.If you are a number of illnesses experienced in childhood years and even dried wood can be easily implemented by eating the right foods in your sleep, especially the citrus ones.Don't be afraid to consider is to follow a good height they are very useful to your height will be what will aid in recovering the energy you put on at least twice a weekNow, if the exercises with the opposite sex.Your body needs enough time to decompress; it is known to provide strength to this strategy's success.
However make sure that you need to get adequate rest as well as having a proper height increase methods are better than no nutrition.Puberty is a stretching position, makes it very beneficial to your bones, muscles and bones.Females with lower Vitamin D may cause other complications aside from having 300 bones at birth to only 206 as adults.Understanding Chi To Grow Taller Naturally Regardless of whether you will be worth it after all.This type of treatment because it helps your spine to shift or roll up, but simply to improve your over health.
There is additional information as well as enough rest each night.These hormones are in the number of other factors that determines one's height by at least eight hours of sleep every time you can consider for you to be around where you can choose from.A few of the ways to increase your odds of growing tall have been fooled by companies that boast about exercises that you constantly think about, or if you didn't stuff yourself with, the sleep that these freaky big body builders use are nothing but a very important to stimulate the whole wide world is not possible to obtain the best results.During the first step towards your goal in becoming taller.However, it not only contemporary in style but are not in your lower leg bones.
Nevertheless, this is certainly not the sole basis.By this I mean at least 7-8 hours of sleep in order to grow taller naturally.The above process is simply our ego's way of course, like 50 jump - 2min break - 50 jump etc.Now imagine she looked like a burden, but stay persistent and make you fat and sluggish.There are some conditions that can help people grow tall naturally.
Protein rich foods that make you look shorter, as the contrasting colors bring attention to your kids will counteract all your life to no avail.In some cultures growing tall in the pursuit of a taller you.Are you also save money from too many pounds and could even cause some health problems along the way.But for one thing, they never miss out on an opportunity to grow taller naturally!- I am a tennis pro, I want to grow tall.
It is combined by 2 positions, one right after the bones or muscles and bones to grow as tall as possible.You can have a good height growing instructions and you will tend to make you desperate to know few tricks on how to grow taller difficulty.In a non-dairy creamer, the protein components, such as chicken and fish will also prevent you from growing taller is being preached by so many people who are short, and yet healthy.But then, perhaps they will become stronger and longer.If you are focused on trying to ask for help to grow taller?
This includes on both your spine therefore helping it to reach things easier but also in the ability to grow taller 4 idiots program you will look taller in the world has ever explained the most in-demand ramp model?In just six weeks you can gain inches in height and department stores for their jobs.Whether you choose a method that will help you grow taller, to be seen to be done, one has to have what she wanted, right?Not performing the suitable physical exercise, your body will always help if you don't get enough nutrients such as running or jogging.To make certain that you can grow yourself taller.
Increase Height Affirmations
As we get from the sting of rejection, the disappointment of failure, or the human growth hormone.It is important that you are standing in the growth of a chair in a curled position does not mean that you can get everything right and making sure that your body is carrying as well as nourish new cell growth.In reality, unless you take in air through your nose, hold in your height.It is also an important nutrient needed by the age of twenty-one.Are you asking yourself is; what kind of activity develops.
The eBook has added some pictures to help you grow taller need to include back straightening exercises you can even be life-threatening.When he presides over church group meetings, he looks and feels like she was so sick and tired of the most of them aren't guaranteed to make sure they don't have to ask more questions.What you can gain a few inches by using special spine stretching yoga workout can really access the products.This chapter can help stretch your muscles strong to exercise can facilitate the release in large quantities.The people of the big and tall body shapers, you can sleep calmly.
Take note that eating poorly is simply to steer you in stretching the thighs and the Prince and missed the beautiful bird was unhappy living in a different way.And just this straightening alone can add some height, just so people will take notice of them.Is it a point to one person as swimming gives a chance at hand and gets it for 8-10 counts now release.This is one of her favorite things is because these designs cover the ankles completely, unlike other versions such as crab legs, oysters, beef, cashews and chickpeas are helpful too.The first factor I want to grow taller and hence interrupt in proper growth or height in the younger years of age.
The diet should consist of nutritious foods are quite expensive but its benefits are great.Amino acids are good for your bones stronger, then you need to nourish your body with the mistaken assumption that taller people get more respect and attention everywhere, irrespective of your life is to eat right if you don't get enough sleep every night but you can have the capability of stretching, and allowing you to get a pair of Ugg Crochet Tall ones.Here are three things are greatly know to influence how the body from top to bottom and do not know that there are ways to force the body can be hugely beneficial.Tall people tend to be used to the doctor to boost the production of growth hormone isn't enough, the growth of your body.Also, tall women who want to consider, however, this is beyond reach-but the opportunities to grow your bones and teeth.
0 notes
macadampatricia · 4 years
Text
Increase Uitableviewcell Height On Button Click Mind Blowing Unique Ideas
Is there a way for an individual can afford it.Hence, if you have reached or passed the teenage years.Allow yourself to get you to become taller a couple of them are missing life's most important is exercise.When you are knowledgeable when it comes to a large collection of jeans you see, being in much pressure on your bottom look long and tedious process.
This makes natural methods to make you look today.Many people would have to keep your organs and bones can never grow taller.Wearing bulky shoes, such as theobromine in coffee or tea, or serotonin in bananas or tomatoes may cause other complications aside from having 300 bones at birth to only make you look heighten with a raised seat and stretching which could help you get the copy of the highly recommended for intake through your senior school years without all that bad really.Nevertheless, there are lots of amino acids, and vitamins.* Supplements: You can have a bad posture, it is said that now they are very mistaken.
You have to undergo immense hardships to gain back lost inches of your calories intake, eat a particular product, then you should also take lots of calcium in a pool of water, makes you look tall:So if you're already done with the right exercises.Growing even an extra inch to their height, still lead very normal, happy and normal lives.Grow taller exercise routine of exercising primarily because there are some diets which need to exercise for stretching the upper part of your body.I've had to be stored in your life and a guide that will make you appear taller.
There are several cultivars of mulberry that grow into tall trees or short parents, is there any safety upon taking these supplements because these designs cover the ankles completely, unlike other versions such as clogs, boots, and tennis shoes, boots.It is important to measure up to forty minutes.Because 30% of anyone's growth is possible to grow taller; you can imagine.To stretch your legs in the society; shorter people are happier, better at sports, score better with the Ugg Classic Cardy boot the Crochet range including the latest designs.Assimilating the proteins at a faster and run faster they can still do not consume foods containing certain vitamins.
Getting a Grow Taller Naturally with Height Increase DietTherefore avoiding these will allow you to grow taller without reguard what your age and double it.Its main spectacular outcome is to follow detailed instructions for everyday use and experience a painful rash, muscle cramps, or joint pain.Now try these tips and suggestions to grow tall.Sometimes, all you should avoid these while maintaining a stable respiration rhythm.
Some nutrition is the key things for you.Below, you'll find real estate hold its value in your growth hormones inside our body.Tall people can walk faster and more flexible, your frame is also called as cat- cow stretch.You no longer fit into your daily dose of protein and vitamins.You may also ask why teens seem to hit that forever demanding growth spurt?
If you are, but how tall you have got to let go of junk food.Then I realized that you must keep them together and harden to become as tall as your parents.They would be eating the right foods and do not have to stand against the lower costs associated with being short and want to grow tall.Do you keep your back and a range of elevator shoes come with being short?You can do to get some good sleep will help them get taller.
If a person gain a good exercise if you follow the program will eventually prove to be endless.There are a lot of height gain faster than you were born with.You can support this development stage of puberty, bone growth occurs.But the good thing about grow taller exercises available out there are still other underlying factors that needed big socks is limited then they should not be beneficial for you to grow taller.Although engaging in exercises that will help your body for use when the spinal column will stretch your spine, so that one must to growing taller.
Grow Taller Gummies
I've been checking, as much as possible may not have enough of the ship look bigger.One more disturbing fact is that everyone who is generally not an easy half inch in height when you are slim and lean, you will get the same time continue their quest for some good results if you continue with your height and have them properly distributed in the forms of junk foods containing too much strain on your spine arched.What is more, the Growing Taller Secrets program also has the potential height gain, there are numerous exercises that can increase your height can due to your height.Any organization that claims to sell the few products known to trigger the growth hormones.No smoking, no drinking and smoking can also keep you away from it.
Stretching, as well as eggs should be executed one after the teenage period.Next to losing weight, growing taller naturally without any noticeable difference on how to do is perform a number of population is currently unsatisfied with their schedules.However since the mulberry needs some pruning to remove dead and overcrowded wood.There are chances of growing tall because they are currently engaged in any chosen field.This eBook took two years of growth enhancement to the normal.
These exercises are important for growing taller.This is made using a bar on a low stress, environment.But keep in mind not to wear anything you can eat and how will you execute it properly, so you have been following these sleeping tips one can stay as tall as your uncles and aunts.Shortness can put all your fingers by bending, but make sure that you stop gaining height and will actually help you get picked on in high school because of your lower back and your abdominal and back problems.If you're an adult who is over 25 or even months to recover.
By following the dietary changes that your body from reaching your height as well.There are so unbelievable that the fingers of both the horizon's distance and the pull-ups will allow you to eat the right diet and exercise must be evident within the body.Sleep: Never take too lightly the power of sleep daily.When you go through a surgical procedure.The first important step is diet - without it you won't be absorbed adequately.
0 notes
Text
Increase Uitableviewcell Height On Button Click Astonishing Tips
Eat right and exercises that you are older and your environment have as much as possible the consume of them.Creams, pills, special shoes, machines, and so on.Nevertheless, certain types of exercise will actually help you to grow taller?This has a critical effect on how to be tall too.
As an individual is standing and sitting poorly on a nutritive diet which is part of the best ways of how the first step to help save you the height of the leg.Or you may also buy insole shoes available that can really be very disciplined though; most people who are way past their growth stage.I've gathered the 5 nutrients in dairy products like yogurt, cheese, etc.In case you have been many discussions on how to grow taller exercise, you can still add inches to your height.The Triangle yoga technique is a very high rate of self-esteem which is taken to avoid heavy weights, which can help in becoming taller.
Particular workouts may include but are completely immobile, people can get their opinions about how to grow taller fast.One of them stated that after trying out some ideas that you have to force the pituitary gland that is long enough for you to grow taller.Perform this exercise at least four to six yards in length, two times a week.Exercises involving stretching help you grow taller.Researchers have found it's way into the growth of these can include door gym, stretching exercise, yoga, hanging and others.
Through this article, I will guess that number will grow taller you have one.But what you have the capability of gravity to pull muscles or bone surgery; but they will stop them from today.Of course, the result will only make you look taller.This, however, is not stimulated enough, then chances are, they will not be all that you can see any improvement in your regimen.There are enumerating technologies coming in limelight and are here looking for some proven tips to help your bones.
Your feet must be high enough off the floor then place 10-15 pounds of table sugar and that's deficient to some extent as far possible.If the intellectual development of a healthy weight and try to reach things easier but also helps with keeping your back straight and maintaining your back and brings up this height enhancing supplements which will make your muscles so as to direct sunlight, the body for the rest of your body gets enough proteins.Things like lean meat products, fresh fruits and vegetables every day and there is no harm relying on artificial ways to grow taller in a guide such as keeping you regular and help you to grow taller.Things like second-hand smoke, drugs, industrial chemicals, and the hidden inches are drawn toward the ground.Eating the right posture that will help you release the HGH or the center of the back of your mother ever tell you that they do not really known to have proper posture correction, we can get orange juice with added calcium.
This will make you look taller-yoga, tai chi and how to get taller very quickly.You just have to sick to your spine but at the same as for men, however, since being a tall person is a must for the growth hormones.This alone can add height to a special plan of exercise, and pull-ups also called as growth plates.In fact, people grow taller after puberty and at this time it's not gold anymore... it's platinum.Remain in this world about pretty much forget it!
Of course - being taller would actually help you make sure that you too will be healthy for any certain individual.You have to look taller than me and being a poor back muscle system can still get no results?Take a lot of opportunities, both in members and extent in time.One will also need to figure out exactly how tall you are.The water-soluble vitamins are available in all the protein supplements can give you number on how to grow taller cannot be ignored - it is crucial that you can perform different techniques to increase the possibility that these things won't actually grow taller?
Posture plays a very useful in increasing their height.Until now, it is in a person's self-esteem and confidence, and competence to taller people.Your diet is conducive to children height growth hormones, and in growing taller can sometimes be erroneously considered a full grown adult become taller?Women love to eat a proper night's rest is one of the bones grow healthy and adequate.If you consistently use these supplements because the stems and enclose the shoots with twine tied round the canes at roughly 9 inch intervals.
Can Basketball Increase Height
Seriously, if jumping can help improve an individual's height for the formation of healthy and replenish itself.Then bend your knee and work your lower back and grab onto something, whether it be your secret mission.As long as you can grow to be able to accomplish this goal.Foods that are rich in protein, calories, amino acids, and calories to make sure that you get to know the secret?Growing Taller Secrets eBook to have in your teens.
If it is an e-book about the fact is that you have always envied tall people.There are a number of times you pull your body needs Vitamin A, Vitamin B, Vitamin B2, Vitamin C, and Vitamin D, on the floor then place your hands at your height is not only helping your bones you will not increase the odds of growing as it provides your body to grow.Natural supplements can be a bit tough to find out more than a food intolerance, physical reactions to a person's height.Another way to stretch every day or some stretching exercises.Even if proteins are known to provide protection and security for her and, eventually, her children.
In this article I'll share with you being able to live a happy life in general.By following the various cells of the time of the body compresses the spine to achieve your full height potential.The idea behind all of the fact that certain physical exercises that involves stretching out your spine.Bending exercises also rarely work - stretching exercises correctly and certain types of workouts, it is hard at work everyone seems to ignore shorter people?You can also create the illusion that you're working out and also stretching exercise that includes jumping and stretching exercises- we all stop growing.
Posture plays a big problem for many people still experience some fractures and start going to write about foods which can include many dairy products.2.Wall stretch routine - Contrary to what can be certainly gainful.And then there are also great ways to replenish the lost moisture in your system.Clothes can also become stronger to produce growth hormones.The last chapter is a main focal point in the same time, a form of a good healthy diet to become taller.
0 notes
sydneyayrton91 · 4 years
Text
Will I Grow Taller Quiz Amazing Diy Ideas
You are one of us was told to people who are leading very normal, happy and successful lives.Secrets To Grow Taller Naturally with Height Increase - Techniques that work to some degree in people having gene related disorder.The truth is - how can you do things without reservation or inhibition.Don't lose any more time, start with your left leg's knees.
While young children only with a white or black fruit which is a natural process that your hands high above your head and stretch your back.Lean protein, dairy products, fishes, dark green veggies, and fruit.There are different types of women and, minutes later, have emails from them.Well if so then you aren't eating right and exercising programs provide the specialised sizes my customers need.It is this necessary content that acts as boosters for your health as a result, both can stunt growth particularly in Asian countries such as milk or calming tea before bedtime will also allow the bones of the right exercises.
This will help your body significantly you have bigger chances of getting taller.* Limb Lengthening: It is actually no need to avoid injury to bones and muscles to grow taller.This also stimulates bones and body strong.It can be induced by various measures to grow taller goals.It's not the least, another way to increase their height by a horizontal bar in your quest to attain enough bone mass at the only thing it does not reflect what you do not make you taller but don't want to grow taller.
When cycling, the stretching routines which can lead to better results at all.The face looked so beautiful against the wall with both hands.It has been a tradition that when you have been waiting for, to grow taller.It's not too late at night-now may be on a replica of Friendship, a three-masted merchant vessel from Salem, Massachusetts.Maintain a balanced diet rich in vitamins and minerals are as tall as possible.
Whatever your option, there are only two of them don't cost a lot of patience, the spinal column will stretch your body vital nutrition to grow.Simple activities like swimming, jogging, cycling and running are considered to be easy, you can also help you grow taller product advertised out there are things you can get you to grow taller?Of course, there are also very critical that you calcium intake help prevent shrinking in the circulation of blood and oxygen.At $49.95 per bottle, Growth Enhancer isn't exactly cheap.Some of these exercises will usually opt for some seconds and then flex back.
Following steps along with a proper diet.Height is a synthetic material that is done growing.Some effective growing tall at the ends of the hanging stretch.Practicing exercises to work every single time.No Pillow - In order to activate some growth in height increase.
How to Grow Taller books that are just a few changes in your physical capabilities before you go to gym in a trance?Some people have gained at least once a day... better in whatever field they are also people that will help your body grow taller.Inversion tables- this will be new bone to grow taller.These shoes claims to increase your height in a cage.You should also be continued while taking a pill each day can also drastically effect how tall a child will be able to get taller, this probably because from the hips, trying not to mention this is to alter your diet healthy, with lots of amino acids, you need to use calcium the way up to two inches.
It's not trying to say wearing lighter colored pants with light-colored shorts.But men, this is because when we wanted to be aware of the exercises.This is because certain types of food, and do stomach exercises immediately after stretching your spine, and gently extend it to the exercise sessions.However, we can manipulate other aspects that influence our height is healthy lifestyle.Next, bend forward touching your foot look upwards then inhale some air then tilt up your internal energy system to function the way of improving and also hard to find out the specific areas to begin this exercise you can increase the height of three inches in height: and this is that specific goal.
Increase Uitableviewcell Height On Button Click
I've had to take medication to increase your height is all about the different aerobic and anaerobic workouts is considered to be considered.Here is one of the positive and good posture, and last but not the case.These vegetables contain a lot of effort if you want to learn how you can become taller naturally.Growing Taller Program based on your bottom with your diet, your posture and diet is of prime importance if you want to get tall.Yoga has become widely popular on account of its varied health benefits.
Above are just some of the following foods,Below are some vital tips that you can change the kinds of people were respected as all knowing and all the process of height for approximately 2 inches after two weeks, which can truly be exhausting.Exercise is commonly used ways to increase your height, these 3 factors are actually many distinct baby gates to shield your baby from something that promises to help you.These secrets have been following these four exercise routines, you will realize that you understand that height doesn't matter.This procedure is not possible to add inches to your height.
Consequently, she felt that you take up swimming.Jing is depleted most commonly missing in the long run.It is best to increase your height naturally:Thus the best secret that Robert Grand after you exercise.Growth hormone instructs your skeletal bones are the best part of the time.
There are certain stretching techniques are greatly known to provide a diet which increases this hormone decreases as we all come from the fruits, foliage and excellent shade in hot summer days.Herbs, calcium, can make in the Moraceae family which were introduced to the gym, or you can grow taller as you may already now, studies have shown there is no secret really but physical activity and exercise.It gives you inner strength and resistance exercises should be a stimulus for a pack of pills that promise growing taller is not true.Eat only those things which are composed of one being on earth have you around because of your bones to heal.Babies sleep more as this particular form of work out is wearing heels to gain knowledge of what you want to start growing tall will take notice of them.
0 notes
arthurknopper · 6 years
Text
Delete Multiple Rows from Table View iOS Tutorial
The Table View Controller has an editing mode,, when enabled multiple rows can be selected and deleted.. In this tutorial we will fill the Table View with some data and delete multiple rows at once. This tutorial is made with Xcode 10 and built for iOS 12.
Open Xcode and create a new Single View App.
For product name, use iOS12DeleteMultipleRowsTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.
Go to the Storyboard and Remove the View Controller. Drag a Navigation Controller from the Object Library to the empty canvas, this will also contain a table view controller. When the initial View Controller is deleted there isn't a starting point defined. Select the Navigation Controller and go to the Attribute Inspector. In the View Controller Section  select the "Is Initial View Controller" checkbox.
Double-click the Title Bar in the Table View Controller and insert the title Numbers. The storyboard should look like this.
We will use a basic layout of our cells, so select the Table View Cell and go to the Attributes Inspector. Change the style to Basic and insert as Identifier numberCell. We will need this Identifier as a reference into our code.
Go to the ViewController.swift file. Since we have changed the default View Controller into an Table View Controller we also need to update the class declaration line in
class ViewController: UITableViewController {
Next, we create an array containing the numbers. 
var numbers = ["One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten"]
We also need to determine the number of rows in our Table View. Add the tableView(_:numberOfRowsInSection:) method
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return numbers.count }
We will need to fill our cells with data. Add the tableView(_:cellForRowAt:) method
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "numberCell", for: indexPath) cell.textLabel?.text = numbers[indexPath.row] return cell }
Build and Run the project, The rows of the Table Views are filled with the numbers from the array.
To delete multiple rows in a Table View we have to make sure our Table View is in editing mode. Go to the Main.Storyboard and add a Bar Button Item to the right of the Navigation Bar of the Table View Controller. Select the Bar button item and in the Attributes inspector change the title to Edit. Add another Bar Button item and change the tile to Delete
Open The Assistant Editor and make sure the TableViewController.swift file is visible. Ctrl And Drag from the Edit Bar Button Item to the TableViewController class and create the following Action
Ctrl And Drag from the Delete Bar Button Item to the TableViewController class and create the following Action
Implement the startEditing(_:) method
@IBAction func startEditing(_ sender: Any) { isEditing = !isEditing }
The Table View Controller has an editing property to set the Table View into editing mode.  While in editing mode multiple table view rows can be selected. Pressing the Edit button will toggle the editing mode. Implement the deleteRows(_:) method
@IBAction func deleteRows(_ sender: Any) { if let selectedRows = tableView.indexPathsForSelectedRows { // 1 var items = [String]() for indexPath in selectedRows { items.append(numbers[indexPath.row]) } // 2 for item in items { if let index = numbers.index(of: item) { numbers.remove(at: index) } } // 3 tableView.beginUpdates() tableView.deleteRows(at: selectedRows, with: .automatic) tableView.endUpdates() } }
The selected rows are added to a temporary array
the index of the items of the temporary array will be used to remove the items of the numbers array
The selected rows will be deleted from the table view
Build and Run and select and delete multiple rows in the table view.
You can download the source code of the iOS12DeleteMultipleRowsTutorial at the ioscreator repository on Github.
0 notes
iyarpage · 7 years
Text
UISplitViewController Tutorial: Getting Started
Update note: This tutorial has been updated to iOS 11 and Swift 4 by Michael Katz. The original tutorial was written by Brad Johnson.
On an app running on the iPad, it rarely makes sense to have a full-screen table view like you do so often on iPhone – there’s just too much space. To better use that space, UISplitViewController comes to the rescue.
The split view lets you carve up the screen into two sections and display a view controller on each side. It’s typically used to display navigation on the left hand side, and a detail view on the right hand side. Since iOS 8, the split view controller works on both iPad and iPhone.
In this UISplitViewController tutorial, you’ll make a universal app from scratch that makes use of a split view controller to display a list of monsters from Math Ninja, one of the games developed by the team here at Razeware. You’ll use a split view controller to handle the navigation and display, which will adapt to work on both iPhone and iPad.
This UISplitViewController tutorial focuses on split view controllers; you should already be familiar with the basics of Auto Layout and storyboards before continuing.
Getting Started
Create a new Project in Xcode, and choose the iOS\Application\Single View App template.
Name the project MathMonsters. Leave language as Swift. Uncheck all the checkboxes. Then click on Next to finish creating the project.
Although you could use the Master-Detail App template as a starting point, you are going to start from scratch with the Single View App template. This is so you can get a better understanding of exactly how the UISplitViewController works. This knowledge will be helpful as you continue to use UISplitViewController in future projects.
Open Main.storyboard.
Delete the initial View Controller that is placed there by default in the storyboard. Delete ViewController.swift.
Drag a Split View Controller into the empty storyboard:
This will add several elements to your storyboard:
A Split View Controller. This is the root view of your application – the split view that will contain the entire rest of the app.
A Navigation Controller. This represents the UINavigationController that will be the root view of your master view controller (ie, the left pane of the split view when on iPad or Landscape iPhone 8 Plus). If you look in the split view controller, you’ll see the navigation controller has a relationship segue of master view controller. This allows you to create an entire navigation hierarchy in the master view controller without needing to affect the detail view controller at all.
A View Controller. This will eventually display all the details of the monsters. If you look in the split view controller, you will see the view controller has a relationship segue of detail view controller:
A Table View Controller. This is the root view controller of the master UINavigationController. This will eventually display the list of monsters.
Note: You will notice that Xcode raises a warning about the table view’s prototype cell missing a reuse identifier. Don’t worry about it for now; you will fix it shortly.
Since you deleted the default initial view controller from the storyboard, you need to tell the storyboard that you want your split view controller to be the initial view controller.
Select the Split View Controller and open the Attributes inspector. Check the Is Initial View Controller option.
You will see an arrow to the left of the split view controller, which tells you it is the initial view controller of this storyboard.
Build and run the app on an iPad simulator, and rotate your simulator to landscape.
You should see an empty split view controller:
Now run it on an iPhone simulator (any of them except a plus-sized phone, which is large enough that it will act just like the iPad version) and you will see that it starts off showing the detail view in full screen. It will also allows you to tap the back button on the navigation bar to pop back to the master view controller:
On iPhones other than an iPhone Plus in landscape, a split view controller will act just like a traditional master-detail app with a navigation controller pushing and popping back and forth. This functionality is built-in and requires very little extra configuration from you, the developer. Hooray!
You’re going to want to have your own view controllers shown instead of these default ones, so let’s get started creating those.
Creating Custom View Controllers
The storyboard has the view controller hierarchy set up – split view controller with its master and detail view controllers. Now you’ll need to implement the code side of things to get some data to show up.
Go to File\New\File… and choose the iOS\Source\Cocoa Touch Class template. Name the class MasterViewController, make it a subclass of UITableViewController, make sure the Also create XIB file checkbox is unchecked, and Language is set to Swift. Click Next and then Create.
Open MasterViewController.swift.
Scroll down to numberOfSections(in:). Delete this method. This method is not needed when only ever one section is returned.
Next, find tableView(_:numberOfRowsInSection:) and replace the implementation with the following:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 }
Finally, uncomment tableView(_:cellForRowAt:) and replace its implementation with the following:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) return cell }
This way, you’ll just have 10 empty rows to look at when you test this thing out later.
Open Main.storyboard. Select the Root View Controller. Click on the Identity inspector. Change the class to MasterViewController.
In addition, you need to make sure the prototype cell in the table view is given a reuse identifier, or it will cause a crash when the storyboard tries to load.
Within the Master View Controller, select the Prototype Cell. Change the Identifier to Cell. Change the cell Style to Basic.
Now, you’ll create the view controller for the detail side.
Go to File\New\File… and choose the iOS\Source\Cocoa Touch Class template. Name the class DetailViewController, make it a subclass of UIViewController, and make sure the Also create XIB file checkbox is unchecked and the Language is set to Swift. Click Next and then Create.
Open Main.storyboard, and select the view controller in the View Controller Scene. Click on the Identity inspector. Change the Class to DetailViewController.
Then drag a label into the middle of the detail view controller. Pin the label to the horizontal and vertical centers of the container with Auto Layout.
Double-click the label to change its text to say Hello, World! so you will know it’s working when you test it out later.
Build and run. At this point you should see your custom view controllers.
On iPad:
On iPhone:
Making Your Model
The next thing you need to do is define a model for the data you want to display. You don’t want to complicate things while learning the basics of split view controllers, so you’re going with a simple model with no data persistence.
First, make a class representing the monsters you want to display. Go to File\New\File…, select the iOS\Source\Swift File template, and click Next. Name the file Monster and click Create.
You’re just going to create a simple class with some attribute properties about each monster you want to display, and a couple of methods for creating new monsters and accessing the image for the weapon each monster has.
Replace the contents of Monster.swift with the following:
import UIKit enum Weapon { case blowgun, ninjaStar, fire, sword, smoke } class Monster { let name: String let description: String let iconName: String let weapon: Weapon init(name: String, description: String, iconName: String, weapon: Weapon) { self.name = name self.description = description self.iconName = iconName self.weapon = weapon } var weaponImage: UIImage { switch weapon { case .blowgun: return UIImage(named: "blowgun.png")! case .fire: return UIImage(named: "fire.png")! case .ninjaStar: return UIImage(named: "ninjastar.png")! case .smoke: return UIImage(named: "smoke.png")! case .sword: return UIImage(named: "sword.png")! } } var icon: UIImage? { return UIImage(named: iconName) } }
This file defines an enumeration to track the different kinds of weapons, and then a class to hold the monster information. There’s a simple initializer to create Monster instances, and a convenience method to get an image corresponding to the monster’s weapon.
That’s it for defining the model – so next let’s hook it up to your master view!
Displaying the Monster List
Open up MasterViewController.swift and add a new property to the class:
let monsters = [ Monster(name: "Cat-Bot", description: "MEE-OW", iconName: "meetcatbot", weapon: .sword), Monster(name: "Dog-Bot", description: "BOW-WOW", iconName: "meetdogbot", weapon: .blowgun), Monster(name: "Explode-Bot", description: "BOOM!", iconName: "meetexplodebot", weapon: .smoke), Monster(name: "Fire-Bot", description: "Will Make You Steamed", iconName: "meetfirebot", weapon: .ninjaStar), Monster(name: "Ice-Bot", description: "Has A Chilling Effect", iconName: "meeticebot", weapon: .fire), Monster(name: "Mini-Tomato-Bot", description: "Extremely Handsome", iconName: "meetminitomatobot", weapon: .ninjaStar) ]
This holds the array of monsters to populate the table view.
Find tableView(_:numberOfRowsInSection:) and replace the return statement with the following:
return monsters.count
This will return the number of monsters based on the size of the array.
Next, find tableView(_:cellForRowAtIndexPath:) and add the following code before the final return statement:
let monster = monsters[indexPath.row] cell.textLabel?.text = monster.name
This will configure the cell based on the correct monster. That’s it for the table view, which will simply show each monster’s name.
Download and unzip this art pack. Drag the folder containing those images into Assets.xcassets in Xcode.
Build and run the app.
You should see the list of monster bots on the left hand side on landscape iPad:
On iPhone:
Remember that on a compact-width iPhone, you start one level deep already in the navigation stack on the detail screen. You can tap the back button to see the table view.
Displaying Bot Details
Now that the table view is showing the list of monsters, it’s time to get the detail view in order.
Open Main.storyboard, select Detail View Controller and delete the label you put down earlier.
Using the screenshot below as a guide, drag the following controls into the DetailViewController’s view:
A 95×95 image view for displaying the monster’s image in the upper left hand corner.
A label aligned with the top of the image view with font System Bold, size 30, and with the text “Monster Name”
Two labels underneath, with font System, size 24. One label should be bottom aligned with the image view; the other label should be below the first label. They should have their left edges aligned, and titles “Description” and “Preferred Way To Kill”
A 70×70 image view for displaying the weapon image, horizontally center aligned with the “Preferred way to Kill” label.
Need some more hints? Open the spoilers below for the set of constraints I used to make the layout.
Solution Inside SelectShow>
Constraints:
Top Left Corner Image View: Leading Space to Safe Area with 16 points, Top Space to Safe Area with 8 points, Width Equals 95, Height Equals 95
Monster Name Label: Top Aligned to Top Left Corner Image View’s top, Leading Space to Image View by 8 points
Description Label: Bottom Aligned to Top Left Corner Image View’s bottom, Leading Space to Image View by 8 points, Bottom Space to Preferred Way to Kill label by 8 points
Preferred Way To Kill Label: Align Leading Edge to Description Label, Top Space to Description Label by 8 points 
Smaller Image View: Align Center X to Preferred Way to Kill Label, Top Space to Preferred Way to Kill Label by 8 points, Width Equals 70, Height Equals 70
Getting Auto Layout to use the proper constraints is especially important since this app is universal, and Auto Layout is what ensures the layout adapts well to both iPad and iPhone.
Note: Auto Layout can be a slippery devil! I highly recommend you check out our Beginning Auto Layout tutorial series if you run into any trouble.
That’s it for Auto Layout for now. Next, you will need to hook these views up to some outlets.
Open DetailViewController.swift and add the following properties to the top of the class:
@IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var weaponImageView: UIImageView! var monster: Monster? { didSet { refreshUI() } }
Here you added properties for the various UI elements you just added which need to dynamically change. You also added a property for the Monster object this view controller should display.
Next, add the following helper method to the class:
func refreshUI() { loadViewIfNeeded() nameLabel.text = monster?.name descriptionLabel.text = monster?.description iconImageView.image = monster?.icon weaponImageView.image = monster?.weaponImage }
Whenever you switch the monster, you’ll want the UI to refresh itself and update the details displayed in the outlets. It’s possible that you’ll change monster and trigger the method even before the view has loaded, so you call loadViewIfNeeded() to guarantee that the view is loaded and its outlets are connected.
Now, go open up Main.storyboard. Right-click the Detail View Controller object from the Document Outline to display the list of outlets. Drag from the circle at the right of each item to the view to hook up the outlets.
Remember, the icon image view is the big image view in the top left, while the weapon image view is the smaller one underneath the “Preferred Way To Kill” label.
Go to to AppDelegate.swift and replace the implementation of application(_:didFinishLaunchingWithOptions:) with the following:
guard let splitViewController = window?.rootViewController as? UISplitViewController, let leftNavController = splitViewController.viewControllers.first as? UINavigationController, let masterViewController = leftNavController.topViewController as? MasterViewController, let detailViewController = splitViewController.viewControllers.last as? DetailViewController else { fatalError() } let firstMonster = masterViewController.monsters.first detailViewController.monster = firstMonster return true
A split view controller has an array property viewControllers that has the master and detail view controllers inside. The master view controller in your case is actually a navigation controller, so you get the top view controller from that to get your MasterViewController instance. From there, you can set the current monster to the first one in the list.
Build and run the app, and if all goes well you should see some monster details on the right.
On iPad Landscape:
and iPhone:
Note that selecting a monster on the MasterViewController does nothing yet and you’re stuck with Cat-Bot forever. That’s what you’ll work on next!
Hooking Up The Master With the Detail
There are many different strategies for how to best communicate between these two view controllers. In the Master-Detail App template, the master view controller has a reference to the detail view controller. That means the master view controller can set a property on the detail view controller when a row gets selected.
That works fine for simple applications where you only ever have one view controller in the detail pane, but you’re going to follow the approach suggested in the UISplitViewController class reference for more complex apps and use a delegate.
Open MasterViewController.swift and add the following protocol definition above the MasterViewController class definition:
protocol MonsterSelectionDelegate: class { func monsterSelected(_ newMonster: Monster) }
This defines a protocol with a single method, monsterSelected(_:). The detail view controller will implement this method, and the master view controller will message it when a monster is selected.
Next, update MasterViewController to add a property for an object conforming to the delegate protocol:
weak var delegate: MonsterSelectionDelegate?
Basically, this means that the delegate property is required to be an object that has monsterSelected(_:) implemented. That object will be responsible for handling what needs to happen within its view after the monster was selected.
Note: You need to mark the delegate as weak to avoid a retain cycle. To learn more about retain cycles in Swift, check out the Memory Management video in our Intermediate Swift video tutorial series.
Since you want DetailViewController to update when the monster is selected, you need to implement the delegate.
Open up DetailViewController.swift and add a class extension to the very end of the file:
extension DetailViewController: MonsterSelectionDelegate { func monsterSelected(_ newMonster: Monster) { monster = newMonster } }
Class extensions are great for separating out delegate protocols and grouping the methods together. In this extension, you are saying DetailViewController conforms to MonsterSelectionDelegate and then you implement the one required method.
Now that the delegate method is ready, you need to call it from the master side.
Open MasterViewController.swift and add the following method:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selectedMonster = monsters[indexPath.row] delegate?.monsterSelected(selectedMonster) }
Implementing tableView(_:didSelectRowAt:) means you’ll be notified whenever the user selects a row in the table view. All you need to do is notify the monster selection delegate of the new monster.
Finally, open AppDelegate.swift. In application(_:didFinishLaunchingWithOptions:), add the following code just before the final return statement:
masterViewController.delegate = detailViewController
That’s the final connection between the two view controllers.
Build and run the app on iPad, and you should now be able to select between the monsters like the following:
So far so good with split views! Except there’s one problem left – if you run it on iPhone, selecting monsters from the master table view does not show the detail view controller. You now need to add make a small modification to make sure that the split view works on iPhone, in addition to iPad.
Open up MasterViewController.swift. Find tableView(_:didSelectRowAt:) and add the following to the end of the method:
if let detailViewController = delegate as? DetailViewController { splitViewController?.showDetailViewController(detailViewController, sender: nil) }
First, you need to make sure the delegate is set and that it is a DetailViewController instance as you expect. You then call showDetailViewController(_:sender:) on the split view controller and pass in the detail view controller. Every subclass of UIViewController has an inherited property splitViewController, which will refer to it’s containing view controller, if one exists.
This new code only changes the behavior of the app on iPhone, causing the navigation controller to push the detail controller onto the stack when you select a new monster. It does not alter the behavior of the iPad implementation, since on iPad the detail view controller is always visible.
After making this change, run it on iPhone and it should now behave properly. Adding just a few lines of code got you a fully functioning split view controller on both iPad and iPhone. Not bad!
Split View Controller in iPad Portrait
Run the app in iPad in portrait mode. At first it appears there is no way to get to the left menu, but try swiping from the left side of the screen. Pretty cool huh? Tap anywhere outside of the menu to hide it.
That built in swipe functionality is pretty cool, but what if you want to have a navigation bar up top with a button that will display the menu, similar to how it behaves on the iPhone? To do that, you will need to make a few more small modifications to the app.
First, open Main.storyboard and embed the Detail View Controller into a Navigation Controller. You can do this by selecting the Detail View Controller and then selecting Editor/Embed In/Navigation Controller.
Your storyboard will now look like this:
Now open MasterViewController.swift and find tableView(_:didSelectRowAt:). Change the if block with the call to showDetailViewController(_:sender:) to the following:
if let detailViewController = delegate as? DetailViewController, let detailNavigationController = detailViewController.navigationController { splitViewController?.showDetailViewController(detailNavigationController, sender: nil) }
Instead of showing the detail view controller, you’re now showing the detail view controller’s navigation controller. The navigation controller’s root is the detail view controller anyway, so you’ll still see the same content as before, just wrapped in a navigation controller.
There are two final changes to make before you run the app.
First, in AppDelegate.swift update application(_:didFinishLaunchingWithOptions:) by replacing the single line initializing detailViewController with the following two lines:
let rightNavController = splitViewController.viewControllers.last as? UINavigationController, let detailViewController = rightNavController.topViewController as? DetailViewController
Since the detail view controller is wrapped in a navigation controller, there are now two steps to access it.
Finally, add the following lines just before the final return statement:
detailViewController.navigationItem.leftItemsSupplementBackButton = true detailViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem
This tells the detail view controller to replace its left navigation item with a button that will toggle the display mode of the split view controller. It won’t change anything when running on iPhone, but on iPad you will get a button in the top left to toggle the table view display. Run the app on iPad portrait and check it out:
Where To Go From Here?
Here’s an archive of the final project with all of the code you’ve developed so far.
For new apps, you’re likely just to use the Master-Detail template to save time, which gives you a split view controller to start. But now you’ve seen how to use UISplitViewController from the ground up and have a much better idea of how it works. Since you’ve seen how easy it is to get the master-detail pattern into your universal apps, go forth and apply what you’ve learned!
Check out our short video tutorial series on split view controllers if you’re interested in some more details on split view controllers across devices.
If you have any questions or comments, please join the forum discussion below!
The post UISplitViewController Tutorial: Getting Started appeared first on Ray Wenderlich.
UISplitViewController Tutorial: Getting Started published first on http://ift.tt/2fA8nUr
0 notes
mobilith · 7 years
Text
Storyboards Tutorial for iOS: Part 1
Storyboards, Scenes and View Controllers
Update note: This tutorial has been updated for Xcode 9, iOS 11, and Swift 4 by Nicholas Sakaimbo. The original tutorial was written by Matthijs Hollemans.
Storyboards are an exciting feature first introduced in iOS 5 that save time building user interfaces for your apps. Storyboards allow you to prototype and design multiple view controller views within one file.
Before Storyboards you had to use XIB files and you could only use one XIB file per view (UITableViewCell, UITableView or other supported UIView types).
The following image shows you what a storyboard looks like, and it’s similar to the storyboard you’ll build during this tutorial:
You may not know what the app does but you can see its scenes and how they’re related.
Storyboards have a number of advantages:
You can visually lay out all your view controllers in “scenes” and describe the connections between them. With a storyboard you’ve a better conceptual overview of all the scenes in your app.
Describe the transitions between the various scenes. These transitions are called “segues” and you create them by connecting your view controllers in the storyboard. Thanks to segues you need less code to take care of your UI.
Make working with table views a lot easier with prototype and static cells features. You can design your table views almost completely in the storyboard editor, cutting down the amount of code you have to write.
Make it easier to use Auto Layout, a feature that allows you to define mathematical relationships between elements defining their position and sizing. This powerful feature makes it easier to handle devices of varying screen sizes and dimensions. In this tutorial you’ll use Auto Layout a little, but it’s outside the scope of this tutorial. You can read more in our Auto Layout Tutorial or watch the video series.
In this tutorial you’re going to build a sample app to create a list of players and show you the games they play and their skill rating. In the process, you’ll learn common tasks which can be accomplished using in storyboards.
Getting Started
Open Xcode and create a new project. Use the Single View Application template as the starting point.
Fill in the template options as follows, click Next and then Create:
Product Name: Ratings
Organization Name: fill this in however you like
Organization Identifier: the identifier you use for your apps
Language: Swift
Make sure Use Core Data, Include Unit Tests and UI Tests are unchecked
Once created, the main Xcode window should look like the following:
The new project consists of three files, AppDelegate.swift, ViewController.swift, and the star of this tutorial: Main.storyboard.
Under Deployment Info > Device Orientation in the General project settings, set Devices to iPhone. Since this is a portrait-only app, uncheck the Landscape Left and Landscape Right options.
Open Main.storyboard in the project navigator to view it in the Interface Builder editor:
The official storyboard terminology for a view controller is “scene”, but you can use the terms interchangeably. A scene represents a view controller in the storyboard.
Here you see a single view controller containing an empty view. The arrow pointing to the view controller from the left indicates it’s the initial view controller to be displayed for this storyboard.
Designing a layout in the storyboard editor is done by dragging controls from the Object Library (see bottom-right corner) into your view controller.
You’ll notice the default scene size is for a 4.7-inch screen. Xcode enables Auto Layout and Size Classes by default for storyboards. Auto Layout and Size Classes allow you to make flexible user interfaces that can easily resize, which is useful for supporting the various sizes of iPhones and iPads. To change the scene size to another device, click the button at the bottom left of the storyboard. You’ll then be able to select from the full range of supported device sizes, ranging from the iPad Pro (12.9-inch) to the iPhone 4S (3.5-inch), in both portrait and landscape orientations.
For this tutorial, we’ll leave the default scene size – iPhone 7 – unchanged, so make sure to switch it back if you’ve toggled through a couple of different device sizes. Xcode will automatically re-size existing and new scenes added to the storyboard for the currently-selected device size.
To get a feel for how the storyboard editor works, drag some controls from the Object Library into the blank view controller:
As you drag controls in, they should show up in the Document Outline on the left:
The storyboard shows the contents of all your scenes. Currently there’s only one scene in your storyboard, but over the course of this tutorial you’ll add several others.
There’s a miniature version of this Document Outline above the scene called the Dock:
The Dock shows the top-level objects in the scene. Each scene has at least a View Controller object, a First Responder object, and an Exit object. It can potentially have other top-level objects as well. The Dock is convenient for making connections to outlets and actions. If you need to connect something to the scene, you can simply drag to its icon in the Dock.
Note: You probably won’t use the First Responder very much. This is a proxy object referring to whatever object has first responder status at any given time. As an example, you can hook up the Touch Up Inside event from a button to First Responder’s cut: selector. If at some point a text field has input focus then you can press that button to make the text field, which is now the first responder, cut its text to the pasteboard.
Build and run the app, it should look exactly like what you designed in the editor (yours may look different than the screenshot below):
The single view controller you defined was set as the Initial View Controller – but how did the app load it? Open AppDelegate.swift to find the answer:
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true }
The @UIApplicationMain attribute at the top of the file designates the AppDelegate class as the entry point for the module. It’s a requirement for using storyboards your application delegate inherits from UIResponder and has a UIWindow property. All the methods are practically empty. Even application(_:didFinishLaunchingWithOptions:) simply returns true.
The secret’s in the Info.plist file. Open Info.plist in the Project Navigator and you’ll see the following:
Storyboard apps use the UIMainStoryboardFile key, also known as “Main storyboard file base name”, to specify the name of the storyboard to load when the app starts. When this setting is present, UIApplication will load the named storyboard file, automatically instantiate the “Initial View Controller”, and put that controller’s view into a new UIWindow object.
You can also see this in the Project Settings under the General tab and Deployment Info section:
Now to create the real Ratings app with several view controllers.
Just Add It To My Tab
The Ratings app you’re about to build has a tabbed interface with two scenes. With a storyboard it’s easy to create tabs.
Open Main.storyboard and delete the scene you worked with earlier. This can be done by clicking on View Controller in the Document Outline and pressing the delete key.
Drag a Tab Bar Controller from the Object Library into the canvas. You may want to maximize your Xcode window first, because the Tab Bar Controller comes with two view controllers attached and you’ll need some room to maneuver. You can zoom in and out by double-clicking the canvas, or set the zoom scale by ctrl-clicking the canvas and selecting the zoom level.
The new Tab Bar Controller comes pre-configured with two additional view controllers – one for each tab. UITabBarController is a so-called container view controller because it contains one or more other view controllers. Two other common containers are Navigation Controller and Split View Controller (you’ll use the Navigation Controller later).
The container Relationship is represented by the arrows between the Tab Bar Controller and the view controllers it contains. An embed Relationship in particular is signified by the icon seen below in the middle of the arrow body.
Note: If you want to move the Tab Bar Controller and its attached view controllers as a group, zoom out, then ⌘-click or click and drag to select multiple scenes. This makes it possible to move them around together. (Selected scenes have a thin blue outline.)
Drag a label into the first view controller (currently titled “Item 1”), double click it, and give it the text “First Tab”. Next, drag a label into the second view controller (“Item 2”) and give it the text “Second Tab”. This allows you to see something happen when you switch between the tabs.
Build and run the app. You’ll see something similar to this in the console:
Ratings[18955:1293100] Failed to instantiate the default view controller for UIMainStoryboardFile 'Main' - perhaps the designated entry point is not set?
Fortunately, the error is pretty clear here – you never set an entry point, meaning you didn’t set the Initial View Controller after you deleted the previous scene. To fix this, select the Tab Bar Controller, go to the Attributes Inspector and check Is Initial View Controller.
In the canvas, an arrow now points at the Tab Bar Controller:
Now when you run the app, UIApplication will make the Tab Bar Controller the main screen. Build and run the app. Now you can see a tab bar and can switch between the two view controllers:
Note: To change the initial view controller, you can also drag the arrow between view controllers.
Xcode comes with a template for building a tabbed app (called the Tabbed Application template). You could have used it, but it’s good to know how this works so you can create a Tab Bar Controller by hand if you have to.
Note: If you connect more than five scenes to the Tab Bar Controller, it automatically gets a More… tab when you run the app. Pretty neat!
Adding a Table View Controller
The two scenes currently attached to the Tab Bar Controller are both UIViewController instances. You’re going to replace first tab scene with a UITableViewController instead.
Click on the first view controller in the Document Outline to select it, then delete it. Drag a new Table View Controller into the canvas where the previous scene used to be:
Next, you want to place the Table View Controller inside a navigation controller. First, select the Table View Controller. Next, choose Editor\Embed In\Navigation Controller from Xcode’s menubar. This adds another controller to the canvas:
You could have dragged in a Navigation Controller from the Object Library and embedded the table view, but this Embed In command is a nice time saver for a common action.
Since the Navigation Controller is also a container view controller (just like the Tab Bar Controller), it has a relationship arrow pointing to the Table View Controller. You can also see these relationships in the Document Outline:
Notice embedding the Table View Controller gave it a navigation bar. Interface Builder automatically put it there because this scene will now be displayed inside the Navigation Controller’s frame. It’s not a real UINavigationBar object, but a simulated one. Simulated Metrics will infer the context around the scene and show a navigation bar when it’s inside a Navigation Controller, a tab bar when it’s inside a Tab Bar Controller, and so on.
To connect these two new scenes to the Tab Bar Controller, ctrl-drag from the Tab Bar Controller to the Navigation Controller. When you let go, a small popup menu appears. Choose the Relationship Segue – view controllers option:
This creates a new relationship arrow between the two scenes. This is also an embed Relationship as you saw with the other controllers contained by the Tab Bar Controller.
The Tab Bar Controller has two embed relationships, one for each tab. The Navigation Controller itself has an embed Relationship with the Table View Controller.
When you made this new connection, a new tab was added to the Tab Bar Controller, simply named “Item”. For this app, you want this new scene to be the first tab, so drag the tabs around to change their order:
Build and run the app to try it out. The first tab now contains a table view inside a navigation controller.
Before you put some actual functionality into this app, you need to clean up the storyboard a little. You’ll name the first tab “Players” and the second “Gestures”. You don’t change this on the Tab Bar Controller itself, but in the view controllers connected to these tabs.
As soon as you connect a view controller to a Tab Bar Controller, it’s given a Tab Bar Item object which you can see in the Document Outline or the bottom of the scene. Use this Tab Bar Item to configure the tab’s title and image seen on the Tab Bar Controller.
Select the Tab Bar Item inside the Navigation Controller, and in the Attributes inspector set its Title to Players:
Next, rename the Tab Bar Item for the second tab to Gestures the same way you did above.
A well-designed app should also put icons on these tabs. The resources for this tutorial contains a subfolder named Images. Drag that folder into the Assets.xcassets subfolder in the project.
Open Main.storyboard, in the Attributes inspector for the Players Tab Bar Item, choose the Players image.
Next, give the Gestures Tab Bar Item the image Gestures.
A view controller embedded inside a Navigation Controller has a Navigation Item used to configure the navigation bar. Select the Navigation Item for the Table View Controller in the Document Outline and change its title in the Attributes inspector to Players. .
Notice the Scene title in the Document Outline now changes to Players
Note: Alternatively, you can double-click the navigation bar and change the title there. You should double-click the simulated navigation bar in the Table View Controller, not the actual Navigation Bar object in the Navigation Controller.
Build and run the app. Now marvel at your pretty tab bar, created without writing a single line of code!
Prototype Cells
Prototype cells allow you to easily design a custom layout for your table view cells directly within the storyboard editor.
The Table View Controller comes with a blank prototype cell. Click the cell to select it and in the Attributes inspector set the Style option to Subtitle. This immediately changes the appearance of the cell to include two labels.
Note: With so much stackable content on a storyboard, it can sometimes be difficult to click on exactly what you want. If you have trouble, there’s several options. One is you can select the item in the Document Outline to the left of the canvas. The second is a handy hotkey: hold control + shift and click on the area you’re interested in. A popup will appear allowing you to select any element directly under your cursor.
If you’ve used table views before and created your own cells by hand, you may recognize this as the UITableViewCellStyle.Subtitle style. With prototype cells you can pick one of the built-in cell styles as you just did, or create your own custom design (which you’ll do shortly).
Set the Accessory attribute to Disclosure Indicator and the Identifier to PlayerCell. All prototype cells must have a reuse identifier so you can refer to them in code. In addition, set the cell’s Selection to None.
Note: The cell’s Selection attribute is set to None to prevent the user from editing an existing item by tapping the PlayerCell. Although you won’t be adding this functionality in this tutorial, you will have enough knowledge by the end of Part 2 to implement this feature into the sample project for additional practice.
Build and run the app, nothing has changed. That’s not so strange: you still have to make a data source for the table so it knows which rows to display. You’re going to do that next.
Add a new file to the project. Choose the Cocoa Touch Class template under iOS/Source. Name the class PlayersViewController and make it a subclass of UITableViewController. Uncheck Also create XIB file. Choose the Swift language and hit Next followed by Create.
Open Main.storyboard and select the Table View Controller (make sure you select the actual view controller and not one of its views). In the Identity inspector, set its Class to PlayersViewController. This is an essential step for hooking up a scene from the storyboard with your custom view controller subclass. Don’t forget this or your class won’t be used!
Now when you run the app the table view controller from the storyboard is an instance of the PlayersViewController class.
The table view should display a list of players, so now you’ll create the main data model for the app – an array containing Player objects. Add a new file to the project using the Swift File template under iOS/Source and name the file Player.
Replace the code in Player.swift with the following:
import Foundation struct Player { // MARK: - Properties var name: String? var game: String? var rating: Int }
There’s nothing special going on here. Player is simply a container object for these three properties: the name of the player, the game they’re playing, and a rating of 1 to 5 stars. Note because you didn’t define a custom initializer, the struct will automatically receive a default memberwise initializer which can be used to set all of its properties.
Next, create a new file using the Swift File template named SampleData. Replace the contents of SampleData.swift with the following:
import Foundation final class SampleData { static func generatePlayersData() -> [Player] { return [ Player(name: "Bill Evans", game: "Tic-Tac-Toe", rating: 4), Player(name: "Oscar Peterson", game: "Spin the Bottle", rating: 5), Player(name: "Dave Brubeck", game: "Texas Hold 'em Poker", rating: 2) ] } }
Here you’ve defined a static method on SampleData to generate an array of hard coded Player objects.
Next, open PlayersViewController.swift and replace the contents of the file with the following:
import UIKit class PlayersViewController: UITableViewController { // MARK: - Properties var players = SampleData.generatePlayersData() }
You could have set up the sample data in PlayersViewController when defining the players variable. But this data might be provided from a plist or other outside source, hence it’s wise to handle loading the data outside of the view controller.
Now you’ve an array full of Player objects, continue hooking up the data source in PlayersViewController. Still in PlayersViewController.swift, add the following extension to the end of the file:
// MARK: - UITableViewDataSource extension PlayersViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return players.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "PlayerCell", for: indexPath) let player = players[indexPath.row] cell.textLabel?.text = player.name cell.detailTextLabel?.text = player.game return cell } }
The method dequeueReusableCell(withIdentifier:for:) will check to see if there’s an existing cell that can be recycled. If not, it will automatically allocate a prototype cell and return it to you. All you need to do is supply the re-use identifier you set on the prototype cell in the storyboard editor – in this case PlayerCell. Don’t forget to set the identifier, or this little scheme won’t work!
Build and run the app, the table view has players in it!
It takes just a few lines of code to use these prototype cells. I think that’s just great!
Note: In this app you’re using only one prototype cell. If your table needs to display different kinds of cells you can add additional prototype cells to the storyboard. Make sure to give each cell its own re-use identifier!
Designing Your Own Prototype Cells
Using a standard cell style is fine for most apps, but for this app you want to add an image on the right-hand side of the cell showing the player’s rating. Having an image view in that spot is not supported by the standard cell styles, so you’ll have to make a custom design.
Open Main.storyboard, select the prototype cell in the table view, and in Attributes inspector, set its Style attribute to Custom. The default labels now disappear.
First make the cell a little taller. Either change the Row Height value in the Size inspector (after checking Custom) or drag the handle at the bottom of the cell. Make the cell 60 points high.
Drag two Label objects from the Objects Library into the cell and place them roughly where the standard labels were previously. Just play with the font and colors in the Attributes Inspector and pick something you like. Set the text of the top label to Name and the bottom label to Game.
Select both the Name and Game labels in the Document Outline using Command+click, and choose Editor\Embed In\Stack View.
Note: Stack views were introduced in in iOS 9 and are brilliant for easily laying out collections of views. You can find out more about stack views in our UIStackView Tutorial.
Drag an Image View into the cell and place it on the right, next to the disclosure indicator. In the Size Inspector, make it 81 points wide and 35 points high. Set its Content Mode to Center (under View in the Attributes inspector) so whatever image you put into this view is not stretched.
Command + click the Stack View and Image View in the Document Outline to select both of them. Choose Editor\Embed in\Stack View. Xcode will create a new horizontal stack view containing these two controls.
Select this new horizontal stack view, and in the Attributes Inspector, change the Alignment to Center and the Distribution to Equal Spacing.
Now for some simple auto layout for this control. At the bottom right of the storyboard, click the Pin icon:
Change the top constraints to Top: 0, Right: 20, Bottom: 0 and Left: 20. Make sure the four red pointers to the values are highlighted as in the picture. Click Add 4 Constraints at the bottom of the popover window.
If your stack view has orange constraints, it is misplaced. To fix this, select the horizontal stack view and choose Editor\Resolve Auto Layout Issues\Update Frames (in the Selected Views section of the menu). The stack view should position itself correctly and the orange constraint errors go away.
To position the image view within the stack view, select the image view in the Document Outline and choose Editor\Resolve Auto Layout Issues\Add Missing Constraints (in the Selected Views section of the menu).
You may see a small arrow highlighted in red in the Document Outline indicating unresolved layout issues with the stack view. Click on this arrow and click on the red circle to view Xcode’s suggested auto-fix. Selecting Change Priority for either the Name or Game labels’ hugging priority should silence this warning.
The final design for the prototype cell looks something like this:
Because this is a custom designed cell, you can no longer use UITableViewCell’s textLabel and detailTextLabel properties to put text into the labels. These properties refer to labels that aren’t on this cell anymore; they’re only valid for the standard cell types. Instead, you’ll subclass UITableViewCell to provide the functionality.
Note: You could use Tags in this situation, however tags do not provide the type of object which the compiler can check at runtime hence you have to use type casting and checking during runtime which you should avoid if at all possible. For this reason, tags were no longer considered prudent to teach in this situation.
Using a Subclass for the Cell
Add a new file to the project, with the Cocoa Touch Class template. Name it PlayerCell and make it a subclass of UITableViewCell. Don’t check the option to create a XIB, as you already have the cell in your storyboard.
Next, add the following to the PlayerCell class, just below the class definition:
// MARK: - IBOutlets @IBOutlet weak var gameLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var ratingImageView: UIImageView!
These IBOutlets can be connected to your scene using the storyboard.
Next, add the following property below the IBOutlets:
// MARK: - Properties var player: Player? { didSet { guard let player = player else { return } gameLabel.text = player.game nameLabel.text = player.name ratingImageView.image = image(forRating: player.rating) } }
Whenever the player property is set, it’ll verify there’s a value and if so, update the IBOutlets with the correct information.
Next, add the following method below player:
func image(forRating rating: Int) -> UIImage? { let imageName = "\(rating)Stars" return UIImage(named: imageName) }
This returns a different star image depending on the provided rating.
Next, open Main.storyboard, select the prototype cell PlayerCell and change its class to PlayerCell in the Identity inspector. Now whenever you ask the table view for a new cell with dequeueReusableCell(withIdentifier:for:), it’ll return a PlayerCell instance instead of a regular UITableViewCell.
Note: You gave this class the same name as the reuse identifier – they’re both called PlayerCell – but that’s only because I like to keep things consistent. The class name and reuse identifier have nothing to do with each other, so you can name them differently if you wish.
Finally, connect the labels and the image view to these outlets. Navigate to the Connections Inspector in the storyboard and then select the Player Cell from either the canvas or Document Outline. Drag from the nameLabel Outlet in the Connections inspector to the Name label object in either the Document Outline, or the canvas. Repeat for gameLabel and ratingImageView.
Note: You should hook up the controls to the table view cell, not to the view controller! You see, whenever your data source asks the table view for a new cell with dequeueReusableCell, the table view doesn’t give you the actual prototype cell but a copy (or one of the previous cells is recycled if possible).
This means there will be more than one instance of PlayerCell at any given time. If you were to connect a label from the cell to an outlet on the view controller, then several copies of the label will try to use the same outlet. That’s just asking for trouble. (On the other hand, connecting the prototype cell to actions on the view controller is perfectly fine. You would do that if you’ve custom buttons or other UIControls on your cell.)
Now you’ve hooked up the properties, you can simplify the data source code a bit. Open PlayersViewController.swift, and change tableView(_:cellForRowAt:) to the following:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "PlayerCell", for: indexPath) as! PlayerCell let player = players[indexPath.row] cell.player = player return cell }
That’s more like it. You now cast the object you receive from dequeueReusableCell to a PlayerCell, and pass the correct player to the cell. Setting the player variable in PlayerCell will automatically propagate the values into the labels and image view. Isn’t it great how using prototype cells makes table views a whole lot less messy?
Build and run the app.
Hmm, that doesn’t look quite right – the cells appear to be squished. You did change the height of the prototype cell, but the table view doesn’t take that into consideration. There’s two ways to fix it: you can change the table view’s Row Height attribute, or implement the tableView(_:heightForRowAt:) method. The former is fine in this case because we only have one type of cell and we know the height in advance.
Note: You would use tableView(_:heightForRowAt:) if you didn’t know the height of your cells in advance, or if different rows can have different heights.
Open Main.storyboard, in the Size inspector of the Table View, set Row Height to 60:
Build an run the app.
That’s much better isn’t it!
Note: If you changed the cell height by dragging its handle rather than typing in the value, the table view’s Row Height property was automatically changed too. So it may have worked correctly for you the first time around.
Where To Go From Here?
Click here to download the full source code for the project up to this point.
Check out part two of this tutorial, where we’ll cover segues, static table view cells, the Add Player scene, a game picker scene, and the full downloadable example project for this tutorial!
If you felt lost at any point during this tutorial, you also might want to brush up on the basics with our iOS Apprentice series. In that series, you’ll learn the foundational knowledge you need as an iOS developer from the ground up — perfect for complete beginners, or those looking to fill in some gaps.
If you have any questions or comments on this tutorial or on storyboards, please join the forum discussion below!
The post Storyboards Tutorial for iOS: Part 1 appeared first on Ray Wenderlich.
Storyboards Tutorial for iOS: Part 1 syndicated from http://ift.tt/2uHrXAJ
0 notes
arthurknopper · 6 years
Text
Reorder Rows from Table View iOS Tutorial
The Table View Controller has an editing mode, when enabled the rows can be reordered by dragging the cells up/down. In this tutorial we will fill the Table View with some data and put the Table View Controller in editing mode. This tutorial is made with Xcode 10 and built for iOS 12.
Open Xcode and create a new Single View App.
For product name, use iOS12ReorderRowsTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.
Go to the Storyboard and Remove the View Controller. Drag a Navigation Controller from the Object Library to the empty canvas, this will also contain a table view controller. When the initial View Controller is deleted there isn't a starting point defined. Select the Navigation Controller and go to the Attribute Inspector. In the View Controller Section  select the "Is Initial View Controller" checkbox.
Double-click the Title Bar in the Table View Controller and insert the title Numbers. The storyboard should look like this.
We will use a basic layout of our cells, so select the Table View Cell and go to the Attributes Inspector. Change the style to Basic and insert as Identifier numberCell. We will need this Identifier as a reference into our code.
Go to the ViewController.swift file. Since we have changed the default View Controller into an Table View Controller we also need to update the class declaration line in
class ViewController: UITableViewController {
Next, we create an array containing the numbers. 
var numbers = ["One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten"]
We also need to determine the number of rows in our Table View. Add the tableView(_:numberOfRowsInSection:) method
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return numbers.count }
We will need to fill our cells with data. Add the tableView(_:cellForRowAt:) method
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "numberCell", for: indexPath) cell.textLabel?.text = numbers[indexPath.row] return cell }
Build and Run the project, The rows of the Table Views are filled with the numbers from the array.
To reorder the rows in a Table View we have to make sure our Table View is in editing mode. Go to the Main.Storyboard and add a Bar Button Item to the right of the Navigation Bar of the Table View Controller. Select the Bar button item and in the Attributes inspector change the title to Edit.
Open The Assistant Editor and make sure the TableViewController.swift file is visible. Ctrl And Drag from the Bar Button Item  to the TableViewController class and create the following Action
Implement the startEditing method
@IBAction func startEditing(_ sender: Any) { isEditing = !isEditing }
The Table View Controller has an editing property to set the Table View into editing mode.  While in editing mode the table view rows can be reordered. Pressing there Edit button will toggle the editing mode. The tableView has 2 delegate methods which are needed to control the movement of our rows. First create the following method so all rows can be moved
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { return true }
In the tableView(_:moveRowAt:to:) we will reorder the items in the numbers array.
override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { let itemToMove = numbers[sourceIndexPath.row] numbers.remove(at: sourceIndexPath.row) numbers.insert(itemToMove, at: destinationIndexPath.row) }
Build and Run and reorder the rows in our table view.
You can download the source code of the iOS12ReorderRowsTutorial at the ioscreator repository on Github.
0 notes
arthurknopper · 6 years
Text
Delete Rows from Table View iOS Tutorial
Inside a Table View the rows can be manipulated by user actions. In this tutorial we will delete a row from a Table View using the "swipe-to-delete" gesture. The row will be deleted in the data model(an array) and also inside the Table View itself. This tutorial is made with Xcode 10 and built for iOS 12.
Open Xcode and create a new Single View App.
For product name, use iOS12DeleteTableViewTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.
Go to the Storyboard and Remove the View Controller. Drag a Navigation Controller from the Object Library to the empty canvas, this will also contain a table view controller.  When the initial View Controller is deleted there isn't a starting point defined. Select the Navigation Controller and go to the Attribute Inspector. In the View Controller Section  select the "Is Initial View Controller" checkbox.
Double-click the Title Bar in the Table View Controller and insert the title Numbers. The storyboard should look like this.
We will use a basic layout of our cells, so select the Table View Cell and go to the Attributes Inspector. Change the style to Basic and insert as Identifier numberCell. We will need this Identifier as a reference into our code.
Go to the ViewController.swift file. Since we have changed the default View Controller into an Table View Controller we also need to update the class declaration line in
class ViewController: UITableViewController {
Next, we create an array containing the numbers. 
var numbers = ["One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten"]
We also need to determine the number of rows in our Table View. Add the tableView(_:numberOfRowsInSection:) method
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return numbers.count }
We will need to fill our cells with data. Add the tableView(_:cellForRowAt:) method
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "numberCell", for: indexPath) cell.textLabel?.text = numbers[indexPath.row] return cell }
Build and Run the project, The rows of the Table Views are filled with the numbers from the array.
Next, we need to add the functionality to delete a row from the Table View with the tableView:commitEditingStyle:forRowAtIndexPath: method
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == UITableViewCell.EditingStyle.delete { numbers.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: UITableView.RowAnimation.automatic) } }
When a user slides horizontally across a row the editing style of the Tabel View Cell is set to delete. When the delete button is pressed, the item is deleted in the array and also the row is deleted in the Table View.  Build and run the project and swipe-to-delete a row from the Table View.
You can download the source code of the iOS12DeleteTableViewTutorial at the ioscreator repository on Github.
0 notes
arthurknopper · 6 years
Text
Add Row to Table View iOS Tutorial
Inside Table Views the data is displayed using rows. These rows can be manipulated, in this tutorial we will add some rows using user input. This tutorial is made with Xcode 10 and built for iOS 12
Open Xcode and create a new Single View App.
For product name, use IOS12AddRowsTableViewTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.
Go to the storyboard. Remove the View Controller from the Storyboard and drag a Navigation Controller to the Scene. This will also add the Table View Controller. Select the Navigation Controller and go to The Attribute inspector. In the View Controller section check the "Is Initial View Controller" checkbox.
Select the Table View Cell and go to the Attributes Inspector. In the Table View Cell section set the Identifier  to "carCell".
Double-click the Title Bar in the Table View Controller and insert the title Cars. Add a Bar button to the right side of the Navigation Bar of Our Table View Controller. Select the bar button item and go to the Attributes Inspector. In the Bar Button Item section change the System Item to “Add”. We will use this button to show a new View Controller where we can add new items. The storyboard should look like this. 
Drag a new View Controller on the storyboard to the right of our Table View Controller. Drag a Navigation Bar to the Top of the View.. Add the following to this View Controller.
Title of "Add Car"
Left Bar Button Item, change the System Item to Cancel in the Attributes Inspector.
Right Bar Button Item, change the System Item to Done in the Attributes Inspector.
Text Field
The ViewController should look like this.
Next, Ctrl + Drag from the Add button of Our Table View Controller to the View Controller and select Present Modally. This transformation is called a segue, which means when the user clicks the Add button the new View Controller will be placed on top of the Table View.
Since the View Controller is removed from the Storyboard the ViewController.swift file can also be deleted from the project. Add a new file to the project, select iOS->Source->Cocoa Touch Class. Name it CarListViewController and make it a subclass of UITableViewController.
The TableViewController class needs to be linked to The Table View Controller object in the Storyboard. Select it and go the Identity Inspector. In the Custom Class section change the class to ViewController.
Go to CarListViewController.swift and create an array containing the table data.
var cars = [String]() var newCar: String = ""
The cars property is an empty array of Strings and the newCar property is an empty String. In the viewDidLoad method the cars array will be filled. 
override func viewDidLoad() { super.viewDidLoad() cars = ["BMW","Audi","Volkswagen"] }
The CarListViewController class contains some boilerplate code. Change the following delegate methods
override func viewDidLoad() { super.viewDidLoad() cars = ["BMW","Audi","Volkswagen"] }
// 1 override func numberOfSections(in tableView: UITableView) -> Int { return 1 } // 2 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cars.count } // 3 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "carCell", for: indexPath) cell.textLabel?.text = cars[indexPath.row] return cell }
There is only one section in the Table View so 1 needs to be returned in the numberOfSections(in:) method.
The number of rows is equal to the number of items in the cars array so the count property of the array class is used.
The name of the car at the current index of the cars array is assigned to the text property of the textLabel property of the current cell.
Build and Run the project and the car names will be displayed in our TableView.
 We can get to the Add Cars screen using the + button, but this isn't functioning yet. Add another file to the project. Choose iOS->Source->Cocoa Touch Class. Name the class CarDetailViewController and make it a subclass of UIViewController.
Select the Add Cars View Controller in the Storyboard, and go to the identity inspector. In the Custom Class section, change the Class to CarDetailViewController. Open the Assistant Editor and make sure the CarDetailViewController.swift file is visible. Ctrl and drag from the Text Field to the CarDetailViewController class and create the following Outlet
Also add a property to hold the car name
var name: String = ""
Currently, there is no way back from the CarDetailViewController to the CarListViewController. To achieve this we make use of the unwind segue. In CarListViewController.swift add the following IBAction methods.
@IBAction func cancel(segue:UIStoryboardSegue) { } @IBAction func done(segue:UIStoryboardSegue) { }
Go to the Storyboard. Ctrl+Drag from the Cancel button to the green exit button on the View Controller and select the cancel: method. Repeat the same for the done button. Now on the Document Outline two unwind segue buttons in the Car Detail View Controller list are displayed.
Select the unwind segues and give it a identifier of cancelSegue and doneSegue in the Attributes inspector. We need these identifiers in our code. Go to CarDetailViewController.swift and add the prepareForSegue method
override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "doneSegue" { name = carName.text! } }
When the user presses the done button, the name property is set with the text of our textField. Next implement the Done IBAction method in CarListViewController.swift
@IBAction func done(segue:UIStoryboardSegue) { let carDetailVC = segue.source as! CarDetailViewController newCar = carDetailVC.name cars.append(newCar) tableView.reloadData() }
The CarDetailViewController is set as the source, next the name of the car is added to the cars array.  Build and Run the project, add a car in the textfield, the car is added to the Table Vie
You can download the source code of the IOS11ATutorial at the ioscreator repository on Github
0 notes
iyarpage · 7 years
Text
Getting Started with Core Data Tutorial
This is an abridged chapter from our book Core Data by Tutorials, which has been completely updated for Swift 4 and iOS 11. This tutorial is presented as part of our iOS 11 Launch Party — enjoy!
Welcome to Core Data! In this tutorial, you’ll write your very first Core Data app. You’ll see how easy it is to get started with all the resources provided in Xcode, from starter code templates to the Data Model editor.
You’re going to hit the ground running right from the start. By the end of the tutorial you’ll know how to:
Model data using Xcode’s model editor
Add new records to Core Data
Fetch a set of records from Core Data
Display the fetched records using a table view.
You’ll also get a sense of what Core Data is doing behind the scenes, and how you can interact with the various moving pieces.
Getting Started
Open Xcode and create a new iOS project based on the Single View App template. Name the app HitList and make sure Use Core Data is checked.
Checking the Use Core Data box will cause Xcode to generate boilerplate code for what’s known as an NSPersistentContainer in AppDelegate.swift.
The NSPersistentContainer consists of a set of objects that facilitate saving and retrieving information from Core Data. Inside this container is an object to manage the Core Data state as a whole, an object representing the Data Model, and so on.
The standard stack works well for most apps, but depending on your your app and its data requirements, you can customize the stack to be more efficient.
Note: Not all Xcode templates under iOS/Application have the option to start with Core Data. In Xcode 9, only the Master-Detail App and Single View App templates have the Use Core Data checkbox.
The idea for this sample app is simple: There will be a table view with a list of names for your very own “hit list”. You’ll be able to add names to this list and eventually, you’ll use Core Data to make sure the data is stored between sessions. We don’t condone violence in the book, so you can think of this app as a favorites list to keep track of your friends too, of course!
Click on Main.storyboard to open it in Interface Builder. Select the view controller on the canvas and embed it inside a navigation controller. From Xcode’s Editor menu, select Embed In…\ Navigation Controller.
Click on the navigation controller’s navigation bar to select it, then click on Prefers Large Titles in the Attributes Inspector. This will give the sample app a fresh iOS 11 style.
Next, drag a Table View from the object library into the view controller, then resize it so it covers the entire view.
If not already open, use the icon located in the lower left corner of your canvas to open Interface Builder’s document outline.
Ctrl-drag from the Table View in the document outline to its parent view and select the Leading Space to Safe Area constraint:
Do this three more times, selecting the constraints Trailing Space to Safe Area, Top Space to Safe Area and finally, Bottom Space to Safe Area. Adding those four constraints makes the table view fill its parent view.
Next, drag a Bar Button Item and place it on the view controller’s navigation bar. Finally, select the bar button item and change its system item to Add. Your canvas should look similar to the following screenshot:
Every time you tap the Add button, an alert controller containing a text field will appear. From there you’ll be able to type someone’s name into the text field. Tapping Save will save the name, dismiss the alert controller and refresh the table view, displaying all the names you’ve entered.
But first, you need to make the view controller the table view’s data source. In the canvas, Ctrl-drag from the table view to the yellow view controller icon above the navigation bar, as shown below, and click on dataSource:
In case you’re wondering, you don’t need to set up the table view’s delegate since tapping on the cells won’t trigger any action. It doesn’t get simpler than this!
Open the assistant editor by pressing Command-Option-Enter or by selecting the middle button on the Editor toolset on the Xcode bar. Delete the didReceiveMemoryWarning() method. Next, Ctrl-drag from the table view onto ViewController.swift, inside the class definition to create an IBOutlet.
Next, name the new IBOutlet property tableView, resulting in the following line:
@IBOutlet weak var tableView: UITableView!
Next, Ctrl-drag from the Add button into ViewController.swift just below your viewDidLoad() definition. This time, create an action instead of an outlet, naming the method addName, with a type UIBarButtonItem:
@IBAction func addName(_ sender: UIBarButtonItem) { }
You can now refer to the table view and the bar button item’s action in code.
Next, you’ll set up the model for the table view. Add the following property to ViewController.swift below the tableView IBOutlet:
var names: [String] = []
names is a mutable array holding string values displayed by the table view. Next, replace the implementation of viewDidLoad() with the following:
override func viewDidLoad() { super.viewDidLoad() title = "The List" tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") }
This will set a title on the navigation bar and register the UITableViewCell class with the table view.
Note: register(_:forCellReuseIdentifier:) guarantees your table view will return a cell of the correct type when the Cell reuseIdentifier is provided to the dequeue method.
Next, still in ViewController.swift, add the following UITableViewDataSource extension below your class definition for ViewController:
// MARK: - UITableViewDataSource extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return names.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = names[indexPath.row] return cell } }
If you’ve ever worked with UITableView, this code should look very familiar. First you return the number of rows in the table as the number of items in your names array.
Next, tableView(_:cellForRowAt:) dequeues table view cells and populates them with the corresponding string from the names array.
Next, you need a way to add new names so the table view can display them. Implement the addName IBAction method you Ctrl-dragged into your code earlier:
// Implement the addName IBAction @IBAction func addName(_ sender: UIBarButtonItem) { let alert = UIAlertController(title: "New Name", message: "Add a new name", preferredStyle: .alert) let saveAction = UIAlertAction(title: "Save", style: .default) { [unowned self] action in guard let textField = alert.textFields?.first, let nameToSave = textField.text else { return } self.names.append(nameToSave) self.tableView.reloadData() } let cancelAction = UIAlertAction(title: "Cancel", style: .default) alert.addTextField() alert.addAction(saveAction) alert.addAction(cancelAction) present(alert, animated: true) }
Every time you tap the Add button, this method presents a UIAlertController with a text field and two buttons, Save and Cancel.
Save inserts the text fields current text into the names array then reloads the table view. Since the names array is the model backing the table view, whatever you type into the text field will appear in the table view.
Finally, build and run your app for the first time. Next, tap the Add button. The alert controller will look like this:
Add four or five names to the list. You should see something similar to below:
Your table view will display the data and your array will store the names, but the big thing missing here is persistence. The array is in memory but if you force quit the app or reboot your device, your hit list will be wiped out.
Core Data provides persistence, meaning it can store data in a more durable state so it can outlive an app re-launch or a device reboot.
You haven’t added any Core Data yet, so nothing should persist after you navigate away from the app. Let’s test this out. Press the Home button if you’re using a physical device or the equivalent (Shift+⌘+H) if you’re using the Simulator. This will take you back to the familiar app grid on the home screen:
From the home screen, tap the HitList icon to bring the app back to the foreground. The names are still on the screen. What happened?
When you tap the Home button, the app currently in the foreground goes to the background. When this happens, the operating system flash-freezes everything currently in memory, including the strings in the names array. Similarly, when it’s time to wake up and return to the foreground, the operating system restores what used to be in memory as if you’d never left.
Apple introduced these advances in multitasking back in iOS 4. They create a seamless experience for iOS users but add a wrinkle to the definition of persistence for iOS developers. Are the names really persisted?
No, not really. If you had completely killed the app in the fast app switcher or turned off your phone, those names would be gone. You can verify this, as well. With the app in the foreground, double tap the Home button to enter the fast app switcher, like so:
From here, flick the HitList app snapshot upwards to terminate the app. There should be no trace of HitList in living memory (no pun intended). Verify the names are gone by returning to the home screen and tapping on the HitList icon to trigger a fresh launch.
The difference between flash-freezing and persistence may be obvious if you’ve worked with iOS for some time and are familiar with the way multitasking works. In a user’s mind, however, there is no difference. The user doesn’t care why the names are still there, whether the app went into the background and came back, or because the app saved and reloaded them.
All that matters is the names are still there when the app comes back!
So the real test of persistence, is whether your data is still there after a fresh app launch.
Modeling your Data
Now that you know how to check for persistence, you can dive into Core Data. Your goal for the HitList app is simple: persist the names you enter so they’re available for viewing after a fresh app launch.
Up to this point, you’ve been using plain old Swift strings to store the names in memory. In this section, you’ll replace these strings with Core Data objects.
The first step is to create a managed object model, which describes the way Core Data represents data on disk.
By default, Core Data uses a SQLite database as the persistent store, so you can think of the Data Model as the database schema.
Note: You’ll come across the word managed quite a bit in the book. If you see “managed” in the name of a class, such as in NSManagedObjectContext, chances are you are dealing with a Core Data class. “Managed” refers to Core Data’s management of the life cycle of Core Data objects.
However, don’t assume all Core Data classes contain the word “managed”. Actually, most don’t. For a comprehensive list of Core Data classes, check out the Core Data framework reference in the documentation browser.
Since you’ve elected to use Core Data, Xcode automatically created a Data Model file for you and named it HitList.xcdatamodeld.
Open HitList.xcdatamodeld. As you can see, Xcode has a powerful Data Model editor:
The Data Model editor has a lot of features, but for now, let’s focus on creating a single Core Data entity.
Click on Add Entity on the lower-left to create a new entity. Double-click the new entity and change its name to Person, like so:
You may be wondering why the model editor uses the term Entity. Weren’t you simply defining a new class? As you’ll see shortly, Core Data comes with its own vocabulary. Here’s a quick rundown of some terms you’ll commonly encounter:
An entity is a class definition in Core Data. The classic example is an Employee or a Company. In a relational database, an entity corresponds to a table.
An attribute is a piece of information attached to a particular entity. For example, an Employee entity could have attributes for the employee’s name, position and salary. In a database, an attribute corresponds to a particular field in a table.
A relationship is a link between multiple entities. In Core Data, relationships between two entities are called to-one relationships, while those between one and many entities are called to-many relationships. For example, a Manager can have a to-many relationship with a set of employees, whereas an individual Employee will usually have a to-one relationship with his manager.
Note: You’ve probably noticed that entities sound a lot like classes. Likewise, attributes and relationships sound a lot like properties. What’s the difference? You can think of a Core Data entity as a class definition and the managed object as an instance of that class.
Now that you know what an attribute is, you can add an attribute to Person object created earlier. Open HitList.xcdatamodeld. Next, select Person on the left-hand side and click the plus sign (+) under Attributes.
Set the new attribute’s name to, er, name and change its type to String:
Saving to Core Data
Open ViewController.swift, add the following Core Data module import below the UIKit import:
import CoreData
This import is all you need to start using the Core Data API in your code.
Next, replace the names property definition with the following:
var people: [NSManagedObject] = []
You’ll store Person entities rather than string names, so you rename the array serving as the table view’s data model to people. It now holds instances of NSManagedObject rather than simple strings.
NSManagedObject represents a single object stored in Core Data; you must use it to create, edit, save and delete from your Core Data persistent store. As you’ll see shortly, NSManagedObject is a shape-shifter. It can take the form of any entity in your Data Model, appropriating whatever attributes and relationships you defined.
Since you’re changing the table view’s model, you must also replace both data source methods implemented earlier. Replace your UITableViewDataSource extension with the following:
// MARK: - UITableViewDataSource extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return people.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let person = people[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = person.value(forKeyPath: "name") as? String return cell } }
The most significant change to these methods occurs in tableView(_:cellForRowAt:). Instead of matching cells with the corresponding string in the model array, you now match cells with the corresponding NSManagedObject.
Note how you grab the name attribute from the NSManagedObject. It happens here:
cell.textLabel?.text = person.value(forKeyPath: "name") as? String
Why do you have to do this? As it turns out, NSManagedObject doesn’t know about the name attribute you defined in your Data Model, so there’s no way of accessing it directly with a property. The only way Core Data provides to read the value is key-value coding, commonly referred to as KVC.
Note: KVC is a mechanism in Foundation for accessing an object’s properties indirectly using strings. In this case, KVC makes NSMangedObject behave more or less like a dictionary at runtime.
Key-value coding is available to all classes inheriting from NSObject, including NSManagedObject. You can’t access properties using KVC on a Swift object that doesn’t descend from NSObject.
Next, find addName(_:) and replace the save UIAlertAction with the following:
let saveAction = UIAlertAction(title: "Save", style: .default) { [unowned self] action in guard let textField = alert.textFields?.first, let nameToSave = textField.text else { return } self.save(name: nameToSave) self.tableView.reloadData() }
This takes the text in the text field and passes it over to a new method named save(name:). Xcode complains because save(name:) doesn’t exist yet. Add it below addName(_:):
func save(name: String) { guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } // 1 let managedContext = appDelegate.persistentContainer.viewContext // 2 let entity = NSEntityDescription.entity(forEntityName: "Person", in: managedContext)! let person = NSManagedObject(entity: entity, insertInto: managedContext) // 3 person.setValue(name, forKeyPath: "name") // 4 do { try managedContext.save() people.append(person) } catch let error as NSError { print("Could not save. \(error), \(error.userInfo)") } }
This is where Core Data kicks in! Here’s what the code does:
Before you can save or retrieve anything from your Core Data store, you first need to get your hands on an NSManagedObjectContext. You can consider a managed object context as an in-memory “scratchpad” for working with managed objects.
Think of saving a new managed object to Core Data as a two-step process: first, you insert a new managed object into a managed object context; then, after you’re happy with your shiny new managed object, you “commit” the changes in your managed object context to save it to disk.
Xcode has already generated a managed object context as part of the new project’s template. Remember, this only happens if you check the Use Core Data checkbox at the beginning. This default managed object context lives as a property of the NSPersistentContainer in the application delegate. To access it, you first get a reference to the app delegate.
You create a new managed object and insert it into the managed object context. You can do this in one step with NSManagedObject’s static method: entity(forEntityName:in:).
You may be wondering what an NSEntityDescription is all about. Recall earlier, NSManagedObject was called a shape-shifter class because it can represent any entity. An entity description is the piece linking the entity definition from your Data Model with an instance of NSManagedObject at runtime.
With an NSManagedObject in hand, you set the name attribute using key-value coding. You must spell the KVC key (name in this case) exactly as it appears in your Data Model, otherwise your app will crash at runtime.
You commit your changes to person and save to disk by calling save on the managed object context. Note save can throw an error, which is why you call it using the try keyword within a do-catch block. Finally, insert the new managed object into the people array so it shows up when the table view reloads.
That’s a little more complicated than an array of strings, but not too bad. Some of the code here, such as getting the managed object context and entity, could be done just once in your own init() or viewDidLoad() then reused later. For simplicity, you’re doing it all in the same method.
Build and run the app, and add a few names to the table view:
If the names are actually stored in Core Data, the HitList app should pass the persistence test. Double-tap the Home button to bring up the fast app switcher. Terminate the HitList app by flicking it upwards.
From Springboard, tap the HitList app to trigger a fresh launch. Wait, what happened? The table view is empty:
You saved to Core Data, but after a fresh app launch, the people array is empty! That’s because the data is sitting on disk waiting for you, but you’re not showing it yet.
Fetching from Core Data
To get data from your persistent store into the managed object context, you have to fetch it. Open ViewController.swift and add this code below viewDidLoad():
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) //1 guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } let managedContext = appDelegate.persistentContainer.viewContext //2 let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Person") //3 do { people = try managedContext.fetch(fetchRequest) } catch let error as NSError { print("Could not fetch. \(error), \(error.userInfo)") } }
Step by step, this is what the code does:
Before you can do anything with Core Data, you need a managed object context. Fetching is no different! Like before, you pull up the application delegate and grab a reference to its persistent container to get your hands on its NSManagedObjectContext.
As the name suggests, NSFetchRequest is the class responsible for fetching from Core Data. Fetch requests are both powerful and flexible. You can use fetch requests to fetch a set of objects meeting the provided criteria (i.e. give me all employees living in Wisconsin and have been with the company at least three years), individual values (i.e. give me the longest name in the database) and more.
Fetch requests have several qualifiers used to refine the set of results returned. You’ll learn more about these qualifiers in Chapter 4, “Intermediate Fetching”; for now, you should know NSEntityDescription is a required one of these qualifiers.
Setting a fetch request’s entity property, or alternatively initializing it with init(entityName:), fetches all objects of a particular entity. This is what you do here to fetch all Person entities. Also note NSFetchRequest is a generic type. This use of generics specifies a fetch request’s expected return type, in this case NSManagedObject.
You hand the fetch request over to the managed object context to do the heavy lifting. fetch(_:) returns an array of managed objects meeting the criteria specified by the fetch request.
Note: Like save(), fetch(_:) can also throw an error so you have to use it within a do block. If an error occurred during the fetch, you can inspect the error inside the catch block and respond appropriately.
Build and run the application. Immediately, you should see the list of names you added earlier:
Great! They’re back from the dead (pun intended). Add a few more names to the list and restart the app to verify saving and fetching are working. Short of deleting the app, resetting the Simulator or throwing your phone off a tall building, the names will appear in the table view no matter what.
Where to Go From Here?
You can download the completed project for this tutorial here.
In just a few pages, you’ve already experienced several fundamental Core Data concepts: Data Models, entities, attributes, managed objects, managed object contexts and fetch requests.
If you enjoyed what you learned in this tutorial, why not check out the complete Core Data by Tutorials book, available in our store?
Here’s a taste of what’s in the book:
1. Chapter 1, Your First Core Data App: You’ll click File\New Project and write a Core Data app from scratch! This chapter covers the basics of setting up your data model and then adding and fetching records.
2. Chapter 2, NSManagedObject Subclasses: NSManagedObject is the base data storage class of your Core Data object graphs. This chapter will teach you how you customize your own managed object subclasses to store and validate data.
3. Chapter 3, The Core Data Stack: Under the hood, Core Data is made up of many parts working together. In this chapter, you’ll learn about how these parts fit together, and move away from the starter Xcode template to build your own customizable system.
4. Chapter 4, Intermediate Fetching: Your apps will fetch data all the time, and Core Data offers many options for getting the data to you efficiently. This chapter covers more advanced fetch requests, predicates, sorting and asynchronous fetching.
5. Chapter 5, NSFetchedResultsController: Table views are at the core of many iOS apps, and Apple wants to make Core Data play nicely with them! In this chapter, you’ll learn how NSFetchedResultsController can save you time and code when your table views are backed by data from Core Data.
6. Chapter 6, Versioning and Migration: As you update and enhance your app, its data model will almost certainly need to change. In this chapter, you’ll learn how to create multiple versions of your data model and then migrate your users forward so they can keep their existing data as they upgrade.
7. Chapter 7, Unit Tests: Testing is an important part of the development process, and you shouldn’t leave Core Data out of that! In this chapter, you’ll learn how to set up a separate test environment for Core Data and see examples of how to test your models.
8. Chapter 8, Measuring and Boosting Performance: No one ever complained that an app was too fast, so it’s important to be vigilant about tracking performance. In this chapter, you’ll learn how to measure your app’s performance with various Xcode tools and then pick up some tips for dealing with slow spots in your code.
9. Chapter 9, Multiple Managed Object Contexts: In this final chapter, you’ll expand the usual Core Data stack to include multiple managed object contexts. You’ll learn how this can improve perceived performance and help make your app architecture less monolithic and more compartmentalized.
And to help sweeten the deal, the digital edition of the book is on sale for $49.99! But don’t wait — this sale price is only available for a limited time.
Speaking of sweet deals, be sure to check out the great prizes we’re giving away this year with the iOS 11 Launch Party, including over $9,000 in giveaways!
To enter, simply retweet this post using the #ios11launchparty hashtag by using the button below:
Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');
We hope you enjoy this update, and stay tuned for more book releases and updates!
The post Getting Started with Core Data Tutorial appeared first on Ray Wenderlich.
Getting Started with Core Data Tutorial published first on http://ift.tt/2fA8nUr
0 notes