"We all love Paul Hegarty." Stanford IOS8 public class personal note 2 Xcode, Auto layout, and MVC

Source: Internet
Author: User

The original link does not know where,

And then, in the last word, what about MVC in the previous speech, and how does MVC apply to IOS8 development? Paul Hegarty showed us a demo of the calculator, first a new project, the teacher put Appdelegate.swift, launchscreen.xib and images.xcassests files into the supporting Files folder, then the remaining two files Viewcontroller.swift is the C (Controller) in MVC , and Main.storyboard is the V (view) in MVC.

In Main.storyboard we can make the layout of the page, using the drag-and-drop method completely instead of setting the control's position through the code.

and the role of Viewcontroller is that we use it to control the program, such as clicking on the button to display the content will be updated, click on the algorithm will output the results and so on.

When our engineering becomes complex, there will be a lot of great white chunks, which we call the scene (scenes). A scene represents a full display of the phone screen, now I want to add something to the interface, the right side of storyboard called utilities (tool) area

The bottom part of the show is called the Object library. Our calculator display count certainly does not allow us to enter, so we need to be the label, drag when the screen will appear a lot of blue words, these blue words will help us to place the control in the position we want. The small squares around the object indicate that it is selected:

by double-clicking to modify its initial properties, the calculator's display interface is usually initially displayed as 0, we modify it to 0:

When you can't directly edit the contents of the object you dragged onto the page, you can choose to use the Utilities Windows (tool window) on the right, and we'll take a closer look at the tabs in the window:

1.

Represents size Inspector (dimension inspector) for setting dimensions

2.

On behalf of Attributies Inspector (property inspector), it is very important that this is an object-oriented inspector, and when you select something different, the user will see the interface change. For example, the calculator shows 0, in fact, should be on the right side of the label, the number is from the right out, we can operate alignment (calibration)

or change its size by font:

This is how we build the user interface, very intuitive and very object-oriented.

You can select the device you want to run in the upper-left corner and run your program:

The first is the real machine debugging, of course, there is still no connection to the real state, the following devices are virtual, select the device and then click on the Play button (that is, the small triangle)

I usually like to use shortcut keys Commend+r

After running to find a very interesting question, you do not see your storyboard in the 0, we put the virtual iphone6 and storyboard in the screen left-justified look:

0 is actually there, but it's running out of the screen! Now let's solve this problem, why 0 will run to the outside of the screen, this is because our screen in the storyboard is square, no phone's screen is square. This time we need to be constrained to solve this problem, the effect of the constraint is when our screen is squashed when our control how to handle, whether horizontal or vertical flattening.

For our label, we want to be able to fill its screen horizontally regardless of the size of the device, so what we need is the left and right margin of the label, the control key to select the label and then drag to the border, the following options will pop up:

The center item means that the control is centered, and we certainly don't want this, the following options are equivalent to the width of the page, the height and so on, we want to set a small margin ourselves, so select the first item

This time the yellow line and the Orange Line indicate that we have started to abide by the constraint rules of this control, but now you have not told me enough rules, now hint when the page is squeezed when I should do, please tell me.

We continue to select the left and above constraints you will find the color of the box into blue, the indicator has been set up, now only the margin, but we do not want to set the bottom margin, we want the bottom margin according to my following content to adjust:

At any time when you see the Yellow line do not know what to do, click on the bottom left button:

You'll see a new toolbar on the left, called Document Outline, which indicates that the content is related to the controls on the page. It is noteworthy that the small yellow circle on the top right side of it:

Anytime you have a yellow or orange line in the auto-layout, you can see this little yellow circle, and clicking on it will trigger a sliding effect that lists all the questions:

When the cursor moves up, it triggers the right label to be selected, which tells us that the height of the selected font is 38, but we just dragged the label size and its height is now 45, and the dotted line indicates that our label bottom border might want to appear here, However, when we manually drag the one or two pixel difference, when you click on the left side of the yellow triangle, will pop up three processing options:

Update Constraints will force its height to be constrained, which we do not want, so this method is seldom used.

The Reset to suggested Constraints may play a role here, and it will overlap the constraint with the Blue line.

But what you need here is the update Frame, put it where it should be, it lets you preview whether my constraint is appropriate, we select it, click Fix Misplacement, and the problem list on the left has been emptied:

When you return to the document outline, you can see that the small yellow circle is gone. Run it again and see!

Ha, 0 has appeared on the right side of the screen.

You can rotate the screen by commend+ the arrow keys, and you can see that the 0 position is automatically in the upper right corner, proving that our restraint is working. So how to correlate the code and try it, the simplest way is to use the button assistant Editor:

Click, look a little crowded, but fortunately our naviation and uitilites are can be hidden, using the upper right corner:

Viewcontroller in this part of the code is now not available, can be deleted (suddenly refreshing a lot ah, it is a teacher, said delete on the delete, I have never deleted-B):

We can create a pointer-like function by dragging and dropping the control into the code, so that we get the instance variables of the elements in the page in our code:

Click Connect to get a line of code:

@IBOutlet weak var display:uilabel!


This variable display is the label on the page , isn't it amazing? The type of link we choose is outlet, which is a type of display, if you want to trigger the action, you can choose action, it is obvious that our digital display only need a display function.

@IBOutlet is not really the swift syntax, this is generated by Xcode, and the left side of the code will have a small dot:

You move the mouse up . Xcode will select the label on the left, which is the part it is associated with. Here you may not understand the meaning of weak, if you come from other languages, then you may have been exposed to garbage collection of some knowledge. All of the objects in Swift are in the heap, all classes, instances of classes are in the heap, Swift has managed the memory for you, you can manage them without pointers, they will automatically clean up, but not garbage collection, but reference counts, count the number of times they are referenced, and these are automatic. First ignore the role of this weak, it is automatically generated by the connection, you need to know how the memory management occurs, and the instance variable here, there is no symbol to mark this is a pointer, it is always a pointer, because the object is stored in the heap, we do not need redundant * or & These other languages are used to indicate pointers to things.

Back to the statement itself, VAR defines an attribute that makes the variable abbreviation, display is the variable name, and Uilabel is its type.

Now we continue to drag a button to the page, its value is changed to 7, as a button on the calculator keyboard.

Adjust its font and size, size can be modified by the size editor, font size positioning 24th, size 64*64. When 7 is pressed we want the label to show its value, which is 7, which is what our controller needs to do. Select the button to control and drag to the controller and then select Action,outlet corresponds to the instance variable, and the action corresponds to a method, what is the method used to do? Click 7 to append a 7 to the label's original number, so this is a append method, and we want to reuse this method, because clicking on any one of the buttons is the same, We are named Appenddigit. Before the message is sent we need to know which button is clicked, but Swift can choose whether there are parameters in the method:

You can choose to have no parameters or sender,sender means to take this button as a parameter, the default type of the parameter is Anyobject:

Here we certainly do not anyobject choose UIButton. If you forget to choose UIButton, you are tragic (say true, I tragedy several times, the error is not good to check, the operation will bounce directly into the appdelegate), triggering event selection touch inside up:

It means that when you touch the button, your finger is still in the range of the button when you lift it up. I got this method when I clicked Connect:

@IBAction func appenddigit (Sender:uibutton) {    }


Similar to Iboutlet, Func is the abbreviation for function, sender is the parameter of the method, and its type is UIButton. This method does not return a value if it has the syntax to write this way:

@IBAction func appenddigit (Sender:uibutton), string{    }


So what is the use of triggering this method, now we create a few more buttons by copying and pasting, using the Blue line to align them with each other, you will find that the copy of the method when they are also copied, you can copy enough three, and then select a row, and copy, so you can quickly widget a keyboard

You need to delete the button, select the right click on the keyboard delete on the line. We drag the keyboard to put it under the label, there will be a blue line labeled below:

Adding a local variable in the code to a method digit indicates the value of the button being clicked:

This time we're using let instead of Var,let defines constants, VAR defines variables, let's features make the code more readable, the best way not to plug too much code, there are too many functions to re-write a method (teacher education is, I find that I often make this mistake so that my own code can only understand it myself. Why don't we just call digit in Java as a constant, because in swift we can quickly define the position of a variable without having to name it.

Let digit = Sender


Now that we need to use the parameters of our method to implement our function, how do we know what we need in sender, which requires a review of the development documentation, which isperfectly embedded in Xcode, a good iOS Programmers must always review the development documentation, hold down the option key and then move the cursor to the content we want to know by clicking on the popup summary:

Click on the reference below to link to its documentation. As with most languages, methods and variables that access an entity use the "." To proceed. Add one after sender. All of its members, why there is so much, because it inherits from a parent class, and its parent class also has inheritance, so that the member variables become a lot of, fortunately as you learn in depth you will know what you need, by entering the first few letters can be selected fewer members. When I enter the CU, there are some options left to see their first few letters are current, the Input tab will be positioned to the first ambiguous letter (this is very useful). Now we want to know what the value is, and output it at the console:

Let digit = Sender.currenttitle        println ("digit = \ (digit)")


By adding "\ ()" To the string, Swift evaluates the content in parentheses and then translates it into the swift output. Run it. Click on the button 5 to see the output of the console:

Wait, Optional ("5") What the hell? The reason is that when we define digit with let, we don't specify its type, does that mean it's an untyped variable? Wrong! Swift is a very very strong type of language, all objects have a type, Swift has a powerful function called type deduction, it can deduce the type through the context, now hold option to select digit to see its type, to show its type is "String?" ”

The meaning of the question mark is optional (can choose), can choose only two values, one is called "not set" (not set), and with nil to indicate that is not set, it is the variable in the non-state value, and the corresponding value is the value of the value of the value type is? The front. So you can think that if the value is assigned, it is a string type. It is a optional type, but can be assigned to nil. Also see a brief introduction to Currenttitle:

is its value a string? Type, the following get indicates that this is a read-only property and cannot be written. We have other ways to set this variable. So how do we get the string in optional, we need to unpack this optional, and we're using "! ”。 But what happens if the values of these optional are nil? The program will crash out!

Then run it again to see:

What do you think? Got the string we wanted. Now we want to export to the label.

Display.text = Nil

The value of Display.text is also selectable, so we assign it to nil without error. Switch

Display.text = display.text! + digit

Pay attention to the back of Display.text! , it is optional, only string can use +, so use! Forced unpacking. Re-run:


This 0 is not very good, I want to add a property to judge it

Swift gave us a hint of a strange error: Our viewcontroller was not initialized. This is because in swift a class is initialized so that all its properties must be initialized, you cannot use an uninitialized property, two methods, an initialization method, a direct assignment, we first use the direct assignment:

var Userisinthemiddleoftypinganumber:bool = False


All code:

Import Uikitclass Viewcontroller:uiviewcontroller {    @IBOutlet weak var display:uilabel!    var Userisinthemiddleoftypinganumber:bool = False    @IBAction func appenddigit (Sender:uibutton) {let                digit = sender.currenttitle!        println ("digit = \ (digit)")        if Userisinthemiddleoftypinganumber {        display.text = display.text! + digit        } else {        display.text = digit            Userisinthemiddleoftypinganumber = True        }        }    }


Operating effect:

OK, this is the point here, we continue to speak, the content is more rich, we have a good understanding

"We all love Paul Hegarty." Stanford IOS8 public class personal note 2 Xcode, Auto layout, and MVC

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.