Can They Know if You Use Auto Click

Update note: Naeem Shaikh updated this tutorial for iOS 12, Xcode 10 and Swift 4.2. Ryan Ackermann wrote the original.

Making apps that await good in whatsoever orientation across multiple devices can be a challenge. If you've experienced this kind of frustration, despair no longer! Auto Layout makes it easy to support different screen sizes in your apps. In this Car Layout tutorial, you'll acquire all nigh constraints and how to apply them.

Notation: Motorcar Layout makes internationalization easy, besides. You no longer take to make new XIBs or storyboards for every language you wish to support, including right-to-left languages such as Hebrew or Standard arabic.

For new iOS developers, hither'southward a quick overview of Car Layout:

At first, Apple fabricated 1 screen size for the iPhone. Developers didn't accept to create flexible interfaces as they only had to fit that 1 size. Today, differently sized devices and more emphasis on landscape way need user interfaces of different sizes. Machine Layout is Apple tree's solution to this problem, enabling UI elements to grow, shrink and motion depending on screen size.

Later in the tutorial, you'll work on a project called Gallery Kit. To access the materials y'all'll need, click the Download Materials button at the pinnacle or bottom of the tutorial. Before y'all get into the project, it's important to get acquainted with Auto Layout.

Getting Oriented to Auto Layout

Before creating a user interface, have a bout of Xcode and Interface Architect. Interface Builder is a graphical tool inside Xcode that allows developers to create UIs using Auto Layout. Here are some of the common features yous'll come up across when using Interface Builder:

  • T-bars are Xcode'southward style of visualizing constraints on a view. In the image below, there are three T-bars representing the push's height, leading and trailing constraints. These bars too indicate whatever warnings or errors by turning yellow or red, respectively.auto layout tutorial

A Simple Example

To start learning the ins and outs of Interface Builder, first create an empty iPhone awarding.

Trivia: When iOS development get-go started, Interface Builder was a dissever and stand-lonely application from Xcode!

Open Xcode, select Create a new Xcode project and select the Single View App template.
auto layout tutorial

Enter Buttons for the Production Proper name. Go out the other options as their defaults and become through the side by side steps to create the project.

auto layout tutorial

Select Main.storyboard and then View Controller Scene in the Certificate Outline. Make certain to enable Use Auto Layout, Use Trait Variations and Use Safe Expanse Layout Guides in the Storyboard'south File inspector:

auto layout tutorial

New from iOS 11: Safe Expanse Layout Guides let you know the area of your content that is visible underneath anything that navigation or other bars might obscure.

It's time to get your hands dirty! The all-time fashion to go comfortable with Auto Layout is to create a user interface. Gear up? Set? Go!

Dynamic Buttons

Click the Library button in the window bar. Notice the Push button row – it's easier to search for the discussion 'button' to do this. Elevate a push button into the white rectangle representing your view controller in the primary window area. Drag in a 2nd push button and position information technology below the first.

Now y'all'll change the groundwork colors of the buttons. Making sure the inspectors panel is open up, click the Attributes inspector and detect the Background option in the View section. Give the upper button a green background and the lower push a xanthous background.

auto layout tutorial

Select the dark-green button and use the Add together New Constraints menu on the bottom-right and enter 40 to make a twoscore-bespeak constraint to its nearest bottom neighbor. Notice the reddish I-bar; clicking this will add together or remove a constraint in that management. Select Add 1 Constraint to really create the constraint for the button. Now select the yellowish button and enter viii to make an 8-point constraint to the bottom of the view controller. Don't forget to select Add 1 Constraint.

auto layout tutorial

Open theAlign bill of fare with the yellow button selected and check Horizontally in Container, then click Add 1 Constraint. Now, select both buttons at the same time using the Shift key and, in the Align carte du jour, cheque Leading Edges. Again, actually install the constraint past clicking Add i Constraint.

auto layout tutorial

You might see a ruby-red circumvolve with an arrow in it on the top-left. Usually, this indicates an issue that you need to fix. Don't worry about this for now. You'll fix it later. :]

Now you'll see how this works at runtime. Add the following method to the form in ViewController.swift:

@IBAction func buttonTapped(_ sender: UIButton) {   if sender.title(for: .normal) == "10" {              sender.setTitle("A very long title for this button", for: .normal)   } else {     sender.setTitle("10", for: .normal)   } }        

This toggles between a long title and a short championship for the button that triggered the event. Connect this action method to both of the buttons in Interface Builder. Control-drag from each push button to the view controller in the Document Outline and select buttonTapped: in the pop-up.

Build and run the app and tap the buttons to see how they deport. Perform the test in both portrait and landscape orientations.

auto layout tutorial
auto layout tutorial

Regardless of which button has the long or short title, the layout satisfies the constraints you accept given information technology:

  • The lower push is center-aligned in the window, horizontally.
  • The lower button sits 8 points from the bottom of the window.
  • The height push button is 40 points in a higher place the lower push and aligned with the lower button.

That is the entire specification for your user interface.

auto layout tutorial

Fourth dimension to Experiment

For fun, remove the Leading Alignment constraint. To do this, select it in the
Document Outline
and press Delete on your keyboard. Then, select both buttons in Interface Builder and from the Align card select the Trailing Edges option.

auto layout tutorial

At present run the app again and notice the differences.

auto layout tutorial

Now remove the Trailing Alignment constraint and, with both buttons selected, choose Align ‣ Horizontal Centers. That will center the top button with respect to the lesser push button. Run the app and see how the buttons human action when you tap them.

auto layout tutorial

Motorcar Layout Problems: Sometimes Xcode tin't automatically resolve the layout you are trying to define. Nigh of the time, Xcode hasn't had a gamble to recalculate the view and you're stuck with an orange box indicating the best approximate of where the layout should be. In this case, clicking the Update Frames button should fix the problem.auto layout tutorial

Sometimes the issue might exist trickier to resolve. Select the Resolve Motorcar Layout Issues button all the way to the correct to see a menu of options that tin assistance by updating your existing constraints, adding missing constraints, resetting your constraints to constraints suggested past Xcode or clearing the constraints so that you can start over.

Using Intrinsic Content Size

The Add New Constraints carte du jour has an Equal Widths choice. If y'all set this constraint on two views, Auto Layout will make both views equally wide, based on which is the largest.

Select both buttons and choose Add New Constraints ‣ Equal Widths. This adds a new constraint to both buttons:

auto layout tutorial

Fifty-fifty though there are two T-bars, in the Document Outline this shows upward as a unmarried Equal Widths constraint:

auto layout tutorial

Run the app and tap the buttons. The buttons e'er have the same width, regardless of which has the largest label.

auto layout tutorial

When both labels are short, the buttons will compress equally. Unless a constraint prevents it, buttons volition size themselves to fit their content. A push or characterization knows how wide and tall information technology is because information technology knows the length and font size of the text information technology displays or, in the case of a button, a combination of text with a background epitome and some padding. That's the intrinsic content size, an of import concept in Motorcar Layout.

You've already seen it in activity with the buttons. Auto Layout asks your controls how large they need to be and lays out the screen based on that information. Usually, you want to use the intrinsic content size, but there are some cases where you lot may not want to practice that. In these cases, you can fix an explicit width or height constraint on a view.

Play around to get a experience for pinning and adjustment views. Recall, you need enough constraints that Motorcar Layout can determine the position and size for all views.

auto layout tutorial

Putting it Into Practice: Gallery Example

You should now understand constraints and how you can build your layouts past forging relationships between the dissimilar views. In the following sections, you'll run into how to use Auto Layout and constraints to create layouts that run across real-world scenarios.

Pretend you desire to make an app that has a gallery of your favorite programmers. It looks like this in landscape and portrait:

auto layout tutorial auto layout tutorial

The screen comprises four equal quarters. Each quarter has an image view and a characterization. How would you approach this?

If you haven't already, download the Gallery Kit project using the Download Materials button at the top or bottom of this tutorial and open up the starter project. The sample project includes the images you'll need to brandish in the gallery.

Open Principal.storyboard and select the iPhone SE size from the View Every bit console on the bottom-left.

auto layout tutorial

From the Library, elevate a plain View object onto the canvas. With the view selected, open the Size inspector and prepare the Width to 160 and Top to 284 points.

Next, in the Attributes inspector, ready the view'south background colour to green:

auto layout tutorial

At that place are 2 reasons why y'all would drop a obviously UIView onto a storyboard. First, you're going to use it as a container for other views, which helps with organizing the content of your scenes. Secondly, information technology's a placeholder for a custom view or control. In the second case, you'll also set its Grade attribute to the name of your own UIView or UIControl bracket.

Select the green view, open up the Add together New Constraints menu and uncheck Constrain to margins. Create four constraints to all four of the dark-green view's nearest neighbors in each management by clicking the crimson I-bars:

auto layout tutorial

This will create four new constraints between the green view and its superview, i for each side of the view. The actual spacing values may be dissimilar, depending on where you placed the view. Y'all don't have to change the values to match the ones above. Click Add together 4 Constraints to end.

Your storyboard should now look something similar this:

auto layout tutorial

The Safe Area

Are y'all wondering why the constraint at the top of the view stops at the condition bar instead of going all the fashion upwards to the top of the screen?

auto layout tutorial

Since iOS vii, the status bar is always on superlative of the view controller — it's no longer a separate bar — then what gives? When you created the constraint, it didn't attach to the superlative of the screen but the superlative of an invisible rectangle called the Safe Area.

The Safe Expanse is the part of the view controller that isn't obscured by any bars like the status, navigation or tab bar. Because the navigation bar has a different summit in landscape, the Safety Area resizes with the bar when the device is rotated. That makes information technology easy to place views relative to the navigation bar. The same goes for tab confined.

This view needs four constraints to go along it in place. Unlike a button or characterization, a obviously UIView does not have an intrinsic content size. You must add constraints to make up one's mind the position and size of each view.

In this case, the size of the view is unsaid past the size of the superview. This layout has leading, abaft, peak and bottom constraints, and these all have fixed lengths. Yous tin encounter this in the Document Outline:

auto layout tutorial

The width of the greenish view is calculated by the formula: width of safety area minus (lxxx + 80); and its height by the formula: height of safe area minus (13 + 163). The constraints are fixed, then the view has no choice just to resize. Once again, your values may be different, depending on where you put the view.

When you rotate the app, the dimensions of the superview change, and so the view's size changes with it. Build and run the app, and then rotate the simulator to see how the view behaves.

auto layout tutorial
auto layout tutorial

Fixed Sizes

You may non e'er want your view to resize when the device rotates, so you lot can use constraints to give the view a fixed width and/or height. Do that now.

Select the green view and click Add New Constraints. In the pop-up, select Width and give it a value of 160; and then select Height and specify its value to be 372:

auto layout tutorial

Click Add 2 Constraints to stop. You've added ii new constraints to the view, a 160-point width constraint and a 372-point height constraint.

Also alter the values in the existing constraints by selecting each one from the Document Outline and modifying their values in the Size inspector. Use these values: top: 13, leading: eighty, abaft: lxxx, lesser: 163.

Run the app. Yep, information technology looks skilful in portrait.

auto layout tutorial

Now rotate to see it in mural. Whoops! Not just does it non look similar you wanted, but the Xcode debug pane has dumped a nasty error message that looks like this at the top:

Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following listing is 1 you don't want.  Attempt this: (one) look at each constraint and attempt to figure out which you don't expect;  (2) detect the lawmaking that added the unwanted constraint or constraints and fix it.  (...) Will attempt to recover by breaking constraint....        

Remember when I said there must be enough constraints and then that Auto Layout can calculate the positions and sizes of all the views? Well, this is an case where there are also many constraints. When you lot get the error "Unable to simultaneously satisfy constraints," it means your constraints are in conflict.

To solve this, remove the Safe Area.trailing = View.trailing at the right and the Rubber Surface area.bottom = View.bottom at the bottom by selecting them in the Document Outline and hit delete.

The storyboard should wait similar this:

auto layout tutorial

Now the view has the right number of constraints to determine its size and position. Run the app and verify that the error message is gone and that the view stays the same size after rotating.

auto layout tutorial
auto layout tutorial

Next, select the green view's superlative constraint and, in the Size inspector, change its Constant to 284. This volition make sure information technology'southward one-half as large as the screen.

Painting the Portraits

From the Library, drag a Label onto the green view. Find that now the guides appear within that dark-green view considering it's the superview for the characterization.

auto layout tutorial

Position the label against the bottom margin, spaced every bit from the guides.

Y'all now demand to add a space constraint to anchor the label confronting the bottom, left and correct of the light-green view, at 20 points distance. Ensuring that the characterization is selected, click the Add New Constraints button. Enter 20 for each of the lesser, left and right constraints, making sure the I-bar is solid, then select Add together 3 Constraints:

auto layout tutorial

Now, in the Attributes inspector, select Center Alignment.

auto layout tutorial

It's important to accept a right and left constraint on UILabels. Otherwise, they volition show outside their superview when the text is likewise long.

Notice that these new constraints are listed under the dark-green view's own Constraints department, not in the principal view.

Adding Images

From the Library, elevate a new Epitome view object onto the storyboard and make the layout look like this:

auto layout tutorial

The image view's top, left, and correct edges are pinned to its superview, just its bottom is connected to the top of the label with a standard spacing of 8 points. If yous're unsure of how to practise this, then follow these steps.

1. Drag an Image view from the Library into the light-green view. Don't worry about its size or position:

auto layout tutorial

2. With the Prototype view selected, click Add New Constraints and choose the following options:

auto layout tutorial

The top, left, and right I-confined are set to 20 points, but the lesser 1 is gear up to 8 points.

The constraints you chose event in a different frame than the epitome view's current position and size. Interface Architect will automatically adjust the frame every bit it adds the constraints.

Now you're set to add images and names to your view. You lot'll use the bundled images included in Assets.xcassets.

Still in Master.storyboard, select the Image view and, in the Attributes inspector, set Ray as the Image. Also set the Content Style to Aspect Fit. And then, set the Background to White Color.

Double click the Characterization, and set its championship to Ray.

Your layout should wait similar this:

auto layout tutorial

Priorities

Detect that the constraints within the green view turned ruddy. This happened the moment you set the image on the image view. Why is your layout invalid? Accept the guesswork out of information technology. Xcode volition tell you what'south wrong.

Click the small-scale cherry-red pointer side by side to View Controller Scene in the Document Outline to view the issues:

auto layout tutorial

Yous have a Content Priority Ambiguity fault. That's a mouthful! Here's what it ways: If neither the epitome view nor the label has a stock-still elevation, and then Automobile Layout doesn't know by how much to scale each if the acme of the green view should change.

Say at some betoken, the green view becomes 100 points taller. How should Auto Layout distribute these new 100 points among the label and the paradigm view? Does the epitome view become 100 points taller while the label stays the same size? Or does the characterization get taller while the image view stays the aforementioned? Practise they both become 50 points extra, or is it split 25/75, twoscore/60, or some other combination?

If yous don't solve this problem, Automobile Layout has to guess, and the results may be unpredictable.

The solution is to change the Content Hugging Priority of the label. You can imagine hugging here to hateful size-to-fit. In other words, the premises of the view will hug the intrinsic content size. A higher value here ways the view will be less likely to grow and more likely to stay the same.

Go into the Size inspector for the label and set the VerticalContent Hugging Priority to 252. That makes information technology i higher than the priority of the prototype view. Every bit a event, when the superview changes size, the image view will be the 1 to resize, and the label will stay the same size.

auto layout tutorial

The T-bars should turn bluish once again and the Auto Layout warnings should have disappeared.

Adding Other Heads

Drag the green view into the chief view'southward meridian-left corner. Recall that the light-green view had horizontal and vertical space constraints that adamant its position in the parent view. It withal has those, and they cause the frame of the view to be misaligned.

To prepare this, use the Resolve Car Layout Problems button and cull Update Constraints Constants. This will update the constraints to match the frame:

auto layout tutorial

The leading constraint now has size of zero, represented by a thick blueish line at the left edge of the window. Although the view sits in the corner, it needs constraints to anchor it there:

Now yous are going to start adding more than views to evidence more people. Select the dark-green view and printing Command-C followed by Command-V to duplicate information technology. Move the indistinguishable into the top-right corner:

Notice that the T-bars are red. When you fabricated the duplicate, it lost its constraints for the 10 and Y position. To fix that, pin the view to the top and the correct edges of the window. Make certain to uncheck Constrain to margins.

auto layout tutorial

Duplicate two more times and put these copies in the bottom-left and bottom-right corners, respectively. The bottom-left view should accept its leading and bottom pinned, while the lesser-right should have its trailing and lesser edges pinned to the superview.

Now it's time to make the screen more than colorful. Select each of the dark-green views and change their backgrounds to a different color. Too modify the label titles and the images view images to represent the programmers. In the finish, your screen should await something like this:

Those are some expert-looking programmers! :]

Run the app on the iPhone SE simulator. Information technology looks good in portrait, but not in landscape:

auto layout tutorial

It should be pretty obvious what went incorrect: Considering you set a fixed width and meridian on the four colored container views, they volition ever take those sizes, regardless of the size of their superview.

Select the fixed width and fixed meridian constraints from all four views and delete them. This is easiest in the Document Outline. If you lot run the app now, you'll get something similar this:

auto layout tutorial

Annotation: Some of the views are larger than others because of the intrinsic content size. The size of the epitome determines how large the image view is. The size of the text determines how large the label is. Taken together with the constraints for the margins, this determines the total size of each view.

50:50 Carve up

To achieve your desired layout, you're going to set up each view's width and height to be 50% of the ViewController's view. In Document Outline, Control-drag from the greenish Ray view to the Safe Expanse view:

While pressing Shift, click Equal Widths and Equal Heights, and and then press Enter. This allows you lot to select multiple items. Once those constraints are active, Ray volition make full the screen, which is not the intention. :]

In the Size inspector, click Edit on the Equal Width to Safety Surface area row in the Sibling & Ancestor Constraints section:

auto layout tutorial

In the multiplier field, enter 0.five and press Enter. This will set the width of Ray'south view to be 50% of Ray'due south container view. Repeat this for the Equal Height to Rubber Expanse row. You should see that Ray is now the right size:

Now echo this for the remaining views. Build and run. Everything looks dandy!

auto layout tutorial

Where to Go From Here?

Download the completed version of the project using the Download Materials button at the superlative or bottom of this tutorial.

Congratulations! Now you know what Machine Layout is all about, and you have some feel with the nuts! There's much more to learn. To keep learning, check out our Automobile Layout tutorial video series.

If you have any questions or comments as y'all go along on your Auto Layout journeying, bring together the forum give-and-take beneath.

andrewstross1967.blogspot.com

Source: https://www.raywenderlich.com/811496-auto-layout-tutorial-in-ios-getting-started

0 Response to "Can They Know if You Use Auto Click"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel