[Stanford 2011] uiview, protocol, and Gesture Recognition

Source: Internet
Author: User

1. autorotation

What happens to the controller during automatic rotation? First, the Controller's view adjusts the frame when the Controller permits it. The shouldautorotatetointerfaceorientation method returns whether the Controller allows the view to rotate automatically based on the device. the automatic rotation interface can be set to vertical, left, and right. You only need to implement this method in the controller. No matter which direction is supported, the bound of the view changes during rotation, the frame of the sub-view changes, and the sub-view of the sub-view changes. What are the rules for these changes? The changed measure is called struts and springs. When the view bound changes, drawrect will not be called by default again.

 

2. structs and springs

Find struts and springs under xcode | inspecttor. The red I-like sign is structs, and the arrow in the middle is springs. The small window on the right looks like a TV screen. It uses an animation to demonstrate the change of the child view when the parent view is changed. The parent view is displayed in white and the Child view is selected in red.

What is structs & Springs used? Spring has two directions in the middle. When the parent view changes the size, both directions change the size. The four structs are used to keep the distance from the parent view edge, that is, our view will become smaller as the parent view grows. 1:

For example, in the middle of struct & Spring, only horizontal springs and upper, left, and right structs are enabled. In this case, the target view will stick to the top of the parent view, by increasing the width, the distance between the left and right edges is maintained, and the lower part is not changed. (That is, a horizontal spring indicates that the view can be expanded in the left and right directions, and a vertical spring indicates that the view can be expanded in the up and down directions. In this example, only horizontal spring is used, indicating that only the left and right sides can be expanded, but not up and down .) Therefore, when the mobile phone changes from landscape to portrait, the parent view of the target view becomes very high, and the target view will remain at the top, and the screen will be much blank.

In struct & spring on the rightmost side, the target view will not be adjusted to keep the original size, but will remain in the upper left corner.

Conclusion: by setting structs & springs, you can specify the rules of the Child view when the parent view is changed. However, some things cannot be done by structs & Springs. For example, if you want to change your calculator from vertical to horizontal, can you simply re-layout it? It may not work. This is where you may use the code. You can call a method in the controller.DidrotatetouserinterfaceorientationYou can control the view layout by yourself.

3. redraw on bounds change? No

What happens to a custom view when bound changes, such as structs and springs, to make the view wider? Will its drawrect be called again? A: No. View Points are extended or squashed due to performance reasons. Therefore, if it is placed under high resolution, there will be a grain sensation. Fortunately, there is a way to control in the view, there isPropertyCalledContentmodeIt describes what the view has done:

There are three main modes: The first is about the location such as upper, lower, and left. They are used to move the pixels of your view to the specified position. This is not structs & Spring. structs & Spring has already happened. Here, my view has become wider, so how can I do the view point before it becomes wider, if contentmode is right, the vertices will be moved to the right.

The second mode is scaling, filling, content filling, and content adaptation. This will stretch the pixel. In the demonstration, we will see that tofill is the default mode, which automatically scales the pixel to fill the new space, which is likely to distort the image, it's often not what you want,

The third is what we often want, re-painting. That is to say, calling drawrect again is the most sensitive item, but its performance is not the best, but its performance is also good,

The default scall is tofill.PropertyCallContentstretchYou can specify the pixels of a sub-view for stretching. For example, a frame cannot be stretched at will, but the middle is empty, just like uibutton, the middle of the button can be stretched because there is no pixel in the middle, but the edge is not allowed, so contentstretch can specify a rectangle in the view to be stretched.

4. initialize uiview

To set some initial states for a custom view, such as contentmode, You can reload the specified initialization method.Initwithfram.However, when the view leaves the storyboard, The init method will not be called. So how should we deal with this situation? The answer is that there is a method calledAwakefromenibWhen the view leaves the storyboard, it will be called, so any code about the settings will be called in these two methods.

The above is the code. With setup, it will be called in init and awakefromnib. (What is the difference between this and viewdidload ?) We do not recommend that you put the settings in the init method, but other places such as setter. do not consider that you must reload initwithframe and awakefromnib.

5. Protocols (1)

The protocol syntax and interface are very similar. Note: first, the Protocol does not have the corresponding @ implementation, and the implementation of the Protocol is in another object. Therefore, the Protocol is a set of methods and properties, and its implementation is completed by other objects. The only syntax should be noted that you can have one protocol dependent on another. In the example, if you want to implement the Protocol Foo, you must implement the Protocol Other and the protocol nsobject, the Protocol nsobject basically includes all nsobject methods. So if the protocol is followed by nsobject in angle brackets, you mean that Foo must be an nsobject implementation .. (I think entering @ property in xcode will automatically add <nsobject>, because almost all IOS objects are nsobject .) Then you start to listen to this method. All methods are required. unless you put it in @ optional, @ optional indicates that the method to listen to is optional, after @ required is met, it becomes necessary again. Therefore, in this Protocol, dosomething, getmanysomethings, and foo are both mandatory, but the two getsomething and dosomethingoptionalwithargument are optional. You can use this protocol, however, these two methods are not implemented.

In addition to nsobject, what can be included in the protocol? The answer is that any object can. The reality is that we have always inherited objects from nsobject, but we do not have to do so, but the protocol is not directly linked to nsobject. Is there any object on iOS inherited from nsobject? The answer is: no.

The Protocol declaration in the header file: the Protocol can have its own header file, such as Foo. h. Only include your own protocol, and then import it to the implementation and usage. However, in most cases, only one object will use the protocol here, so you can put the Protocol in its header file, for example, the scrollviewdelegate protocol is defined in uiscrollview. h, so you can put the protocol in other header files or your own header files.

#import "Foo.h" //importing the header file that declares the Foo @protocol@interface MyClass:NSObject<Foo> //MyClass is saying it implements the Foo @protocol   ...@end

 

Therefore, you have already declared the Protocol Foo, and then the class myclass is used in @ interface to implement the Protocol. In the above Code, the class myclass inherits from nsobject to implement the FOO protocol, so I am declaring the implementation of my FOO protocol. Now I must implement non-optional methods in Foo; otherwise, the compiler will report an error, the compiler will say that unfinished implementations must implement all the methods required in the FOO protocol.

With the declaration of the Protocol and the object that will implement the Protocol, see

(1) variables that declare an ID, such as ID <protocal>, are in the figure id <Foo>, which indicates an object pointing to an unknown class. I can send messages to this type of object in the Protocol without any introspection. the compiler will check for me. For example, id <Foo> OBJ = [[myclass alloc] init] is acceptable, because foo is implemented in myclass, so the compilation will pass. If it is ID <Foo> OBJ = [nsarray array], it is not possible because nsarray does not implement Foo, and an error is reported during compilation.

(2) variables can be declared as above, and ID <Foo> is an unknown class object that can respond to the foo method when the parameter is passed.

(3) You can also have this type of property, such as myfooproperty in the figure above.

6. Protocols (2)

Protocol usage: see

(1) Just like static types, all these things are intended for the compiler to discover bugs and are the same at runtime. the compiler will find implementation methods and send messages when finding them, if no exception is found, an exception is returned.

(2) You can regard the Protocol as a document that allows you to send messages to these id types. It is a document, such as an unknown object, but through the documentation, I know that it implements

Method.

(3) In iOS, the main purpose of the Protocol is to delegate and data source ).

Think back to the first lesson, I mentioned in MVC that view never knows its controller class, because view is generic. For example, it is impossible for uibutton to know what is calculatorviewcontroller, so view needs to talk to Controller in a common way. One method is target action, and the other method is delegate ), delegation is a key point of this course. The data source is also a delegate, but it is specific to the data delegate. Remember that the view does not have data, the view does not have the instance variable property, and the view only has a pointer to the data. They can have property to show how to plot, which may be color or the like, but they do not have the data displayed. It is the Controller's activity, because only the controller can talk to the model, the model provides the data displayed by the view. There is a typical delegate statement. Almost all delegates are weak, because the objects to be delegated are usually the owners or creators of the delegate object, for example, controller often sets itself as a view delegate or data source. You don't want them to use strong pointers to each other, because in this case, the pointer strong on the stack points to other things, in this way, it is difficult to release both of them at the same time, so the view will only point weak to the Controller. If the Controller is no longer there, the view will be useless.

7. Protocols (3)

The following is scrollview. H. It can be seen that it declares the delegation protocol of scrollview. All methods are optional and not fully written.
The following is the real @ interface. Many things except the weak property are removed. Its type is ID <uiscrollviewdelegate> and its name is delegate. The problem is that it is optional, why do I need to use the Protocol? Once again, the Protocol is a document. When you say that you are the delegate of scrollview, you can view the methods that can be implemented by this protocol, so it is a document.

Then, if a class myviewcontroller wants to use scrollview, note that the myviewcontroller class declares the implementation of uiscrollviewdelegate. The myviewcontroller class has an outlet pointing to scrollview. The myviewcontroller class wants to be the delegate of scrollview, so the delegate message is received in scrollview. For example, setter, self. scrollview. Delegate = self of this scrollview sets self as the delegate of scrollview. All methods like viewforzoominginscrollview will be sent to myviewcontroller.

8. Gesture Recognition

How does Gesture Recognition work? Gesture Recognition is an object that monitors click events of a view. When it finds a type of click, such as extrusion, sliding, dragging, and clicking, it will send a message to the gesture recognition handler to respond accordingly.

The most basic class is uigesturerecognizer, Which is abstract, so you never really use it to create an instance. It has many actual subclasses that you actually use to attach to the view.

There are two steps to use Gesture Recognition: Create a gesture recognition and add it to the view. Then, process the gesture when it is recognized. The first step is usually done by the controller. The Controller determines the implementation of its view, such as dragging and clicking. In essence, the two switches are opened, but the processing of gestures is often done by the view, for example, a custom view knows how to handle gestures and internal states, which is much better than a controller. However, we still want the Controller to add gesture recognition to the view, which is a bit like opening the switch. In addition, some gesture processing may be implemented by the controller. The more explicit point is that it involves modifying the model gesture. If you have a gesture that will change the model, the Controller will handle it. Because the view does not see the model, it is usually the Controller that adds a gesture. It is also possible for the view to add a gesture to itself, some views do not make sense if the gesture cannot be recognized, so you can add the gesture yourself. For example, scrollview adds drag and zoom by itself, because scrollview is used to do this. If you cannot drag or zoom, scrollview is meaningless. However, the controller can remove these gestures. If the scrollview does not need to be dragged, the controller can remove the gestures, but usually does not remove them. Gesture control can also be implemented by anyone, but usually controller or view.

//Adding a gusture recognizer to a UIView from a Controller-(void)setPannableView:(UIView *) pannableView{    _pannableView = pannableView;    UIPanGestureRecognizer *pangr = [[UIPanGestureRecognizer alloc] initWithTarget:pannableView action:@selector(pan:)];}

This code is used to add gesture recognition to the view. The view has a list of recognized gestures. This example is an outlet setter. In this example, create a drag gesture recognition, which is a specific uigesturerecognizer subclass called uipangesturerecognizer. Initialization of Gesture Recognition initwithtarget: Action: this is also a target action in a sense, but it is a bit different. Therefore, target is the processor after Gesture Recognition. Here it is the view itself. Then, pan is the message sent to the view, that is, the action is sent to the target, but pan is not the sender. Gesture Recognition calls the message to be sent. Gesture Recognition is the sender. Therefore, you need to go back and ask the gesture recognition details. After that, addgesturerecognizer is called to complete the addition. When a drag occurs, pan is sent to the target, that is, the view itself.

Does Gesture Recognition always pass the data as a parameter? In fact, if you do not write Pan: no parameters are passed in. For example, you do not need to click the parameter. Generally, Pan: is added, so that gesture recognition can recognize yourself.

How to Implement gesture recognition, such as the Pan :? Each gesture provides its own method, for example, dragging provides the following three methods: (1) The first is translationinview, which will give you a coordinate point to tell you, the distance from the last gesture to this point. The first click is the starting point. After moving, it will tell you the distance from the starting point. The starting point can also be reset, then it will tell you an incremental distance; (2) velocityinview tells you the speed at which your fingers move, which refers to the real-time rate, several pixels per second; (3) settranslation, this is the setter of the first method. If it is set back to 0, you will get an incremental update. It is common to reset translation to get incremental results.

In addition to specific gesture recognition, an important abstract Gesture Recognition provides a property called State. Therefore, gesture recognition is a state machine, and all initial states of gesture recognition are possible. If a gesture is short, such as a click, the status changes to recognized, so the processing function is called and the status changes to recognized. If the gesture persists, such as dragging or scaling, at the beginning, the state is began, and the State is changed in the change. When the finger is raised, the state is ended, and the State failed and cancelled are used only when you implement one operation, for example, you set some statuses when you start in, then you track the statuses, And Then undo these statuses when you ended them. We usually do not implement gesture recognition in this way, so we don't need to worry about the status when we want to implement it. Therefore, if our fingers contract a bit, we modify the view and return to the previous state. If we continue to contract, we will continue to modify the view and do not maintain a State. This is much easier to implement. The only difference between failed and cancelled is that you maintain a state until you clear it. Failed And cancelled may occur when one gesture is disturbed by another. For example, if you are dragging, but you have changed to three-finger clicks, or you have called while making gestures, you can cancel the gesture.

//For example, UIPanGestureRecognizer provides 3 methods:-(CGPoint)translationInView:(UIView*)aView;-(CGPoint)velocityInView:(UIView*)aView;-(void)setTanslation:(CGPoint)translation inView:(UIView*)aView;//Also,the base class,UIGestureRecognizer provides this @property@property(readonly)UIGestureRecognizerState state;

Pan: what is it like? Pan only pays attention to moving. In the following code, translation is the drag distance, and the following code is in view, so the parameter self is view. With translation, I want to move something, and then I want to reset the translation to 0, because the next time I drag, I want to move the increment, I don't need the total distance from the start point, as long as the distance of each movement. Because it is reset after every move, every new action comes in as if it has never been moved.

-(void)pan:(UIPanGestureRecognizer*)recognizer{   if((recognizer.state==UIGestureRecognizerStateChanged)||//We‘re going to update our view every time the touch moves (and when the touch ends)      (recognizer.state==UIGestureRecognizerStateEnded) )   {     
CGPoint translation = [recognizer translationInView:self];//"translation" is the cumulative distance this gesture has moved.//move something in myself(I‘m a UIView) by translation.x and translation.y// for example, if I were a graph and my origin was set by an @property called origin self.origin = CGPointMake(self.origin.x+translation.x,self.origin.y+translation.y); [recognizer setTranslation:CGPointZero inView:self];//Here we are resetting the cumulative distance to zero. }}//Now each time this is called,we‘ll get the "incremental" movement of the gesture(Which is what we want).
//If we wanted the "cumulative" movement of the gesture,we would not include this line of code.

Gesture Scaling (pinch): (1) when the scaling starts, it is 1. When the scaling starts, it changes to 1.7, Or something like 0.8. Similarly, the scaling can also be reset, then we get the incremental scaling. (2) It also has a speed (velocity), scaling rate.
The rotation gesture is to press two fingers and then rotate it in radians. It can also be reset without an angle.

The slide gesture (swipe) has several slide types. The slider can both be used. You only need to create a slide recognition, and then set a property to indicate how many fingers need to be recognized.

The properties of gesture scaling, rotation gesture, and sliding gesture are as follows:

 

[Stanford 2011] uiview, protocol, and Gesture Recognition

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.