Customizing the Pull to refresh control using the Swift language

Source: Internet
Author: User
Tags class definition transparent color

Customizing the Pull to refresh control using the Swift language

CSDN Mobile will continue to be the essence of mobile development for you to explore the technical topics of mobile development, including mobile applications, development tools, mobile games and engines, smart hardware, the Internet of things and other aspects. If you want to contribute, participate in content translation work


There are very many applications around the world. To develop new applications, and to attract the attention of users, so that the application can stand out. There is no doubt that the secret to making simple apps stand out is the personalization skills used by the development team (developers and designers), in small details that most developers do not handle. One of these is the Pull-to-refresh control that is visible from the title of this article. I'll show you how to make this control a makeover by using this article.


You know, the Pull-to-refresh control is an activity indicator (often with short information) that appears at the top of the table view during data load. The table view at this point has not completed the refresh. In fact, Pull-to-refresh controls with "please,


Wait ... "informational prompts are similar when a user waits to get and display new content. The most well-known application is e-mail. Drag the message view to the bottom and the mailing list will be refreshed. The control is from the iOS


6.0 are introduced, which are used frequently in countless applications.


If you want to use the Pull-to-refresh control in your app, look for information on how to use it, and you'll definitely find Simon's article, which is a good illustration of everything you want to know. The other side of the Pull-to-refresh control is how to customize a Pull-to-refresh control. This way, you can add different styles to this obscure but important detail and give the app a different perspective.


To make a long story short, take a look at the tips for adding custom content and animations to "replace" the default Pull-to-refresh control with any object you want to add. Note that the following is a demonstration of the steps you are going to follow, and the actual customizations are entirely up to you, rather, by your imagination. At first, it won't be long before you can create a custom Pull-to-refresh control!


Sample App Overview


The following animation is the custom Pull-to-refresh control in this article:


As you can see, there are some simulation data in the table view. Our goal is not to really get the data from the server, but to focus on the process of the refresh. The activity indicator does not appear, instead of the "Appcoda" animation that lasts the same length as the refresh process.


To know when the simulated refresh action is over, I can only tell you that the timer (Nstimer) object is used here. After four seconds, the object ends the refresh action and hides the custom Pull-to-refresh control. The four second in the example is a randomly selected time interval, which is of course for the purpose of demonstrating the method of the custom control in this article. In many cases, data refresh times are shorter than this (especially with high-speed Internet connectivity). Therefore, in real-world applications, do not use timers to display custom Pull-to-refresh controls in order to leave a mark on the user's mind. You know, especially if the app is great and is often used by users, users will have a lot of opportunities to see this control.


As you can see, develop an extremely simple project. But there is no need to start from scratch, as usual, you can download an initial project first. This is the interface design made in the storyboard (storyboard), and there is a interface


Builder file, called Refreshcontents.xib. In the interface I added a custom content to replace the normal Pull-to-refresh control to display the content. In fact, the custom control contains seven label (UILabel) objects. Together to form the word "Appcoda". There is also a custom view (UIView) as a container for these labels. So it is necessary to do a good job of font format, set the constraints correctly. The next thing to do is load the controls in the view controller and handle them in the appropriate way.


So, first download the initial project and use Xcode to open it.


The default Pull-to-refresh control


The first thing to do with the sample app is to display the simulation data in the table view. The downloaded initial project already contains the Iboutlet attribute called Tbldemo, which is used to connect the table view in the storyboard. Therefore, you need to write the proxy (delegate) method and the data source (DataSource) method required for the table view. However, you need to specify the data to be displayed in the table view before doing so. In the Viewcontroller.swift file, add the following line of code inside the class:

}


Run the app again, and when the table view is dragged to the bottom, you'll see the rotated icon appear. But do not expect this control to be hidden back, this feature is not automatically generated. You have to explicitly end the refresh action, but this is something to do later. The current highlight is that the refresh instructions are running well.


As a hint, this control with the Refresh function can be modified with the background color and control color. For example, the following two lines of code run after the effect is that the background is red, the rotation icon is * * *.



Customizing the contents of a control


The key behind the custom Pull-to-refresh control is to add any additional content you want to the control itself, and the added content will be a child view. The so-called extra content in the sample program is the Refreshcontents.xib file. More specifically, Interface.


The content of the builder file looks like this:


As you can see, the View object contains seven labels in turn. Each label corresponds to the "Appcoda" letter.


The next thing to do is very simple: programmatically assign the contents of the. xib file to a property. Rather, copy the View object to the UIView property, and all the tags are placed in one array in turn. By doing this, you can make these views into any animation we want.


Now go deep into the details. First, add the following two-line declaration statement at the beginning of the class:


With the two properties of the new declaration above, let's create a new custom method to load all the contents of the. xib file:


We will continue to improve the custom function above. The next step is to assign the CustomView to the View object loaded above the code. Note that this method, like the one above, gets the child view from an external. xib file, getting an array that contains all these sub-views. Here, the array contains only the custom view objects, that is, those labels that are the custom view sub-view, not the individual view objects that exist outside of the custom view in. xib. Also note the following lines of code, which match the frame of the custom view to the frame with the old control with the refresh function.



The refresh action is triggered when the table view is dragged, and the last exercise in the code above changes the size of the custom control consistent with the known constraints.


Now load all the tags into the labelsarray array. You may have noticed that each tag in the Refreshcontents.xib file is assigned a label. Starting from the left, the label range is from 1 to 7. We will use these labels to access each label individually.



Get! One more thing is to invoke the above function, which is, of course, called in the Viewdidload method:


Finally, there are some important and necessary changes to be made. In the Viewdidload method, set the background color of the refresh control and the control color to a transparent color. Here is the final code after the modification.



Test the app, and when you pull the refresh, you'll see a custom view with a label that replaces the icon by default. Of course there is no animation effect, the following we will achieve animation effect.


Initializing a custom Animation


This is the final animation effect to achieve:


If you look closely, you will find that the entire animation process consists of two sub-processes:


Starting with the first one, each label rotates slightly (45 degrees), while the color of the label text changes. The current rotated label state is restored before the next label starts to rotate. All labels are restored after the rotation process is complete, then scaled together proportionally and then scaled down.


We implement each part of the animation as a separate custom function to keep it simple and easy to understand. Before you do this, declare some new properties that you want to use later.


Here's a brief description of each property:


Isanimating flag Whether the animation process occurs. Use this property to tell if you can start a new animation process (obviously, when an animation starts, we don't want to start a second animation). The Currentcolorindex property is used in another custom function that is implemented. The function has an array that represents the color (the color of the control text), which represents the color of the label text that will be used next. The Currentlabelindex property represents the index of the label in the first sub-procedure of an animation effect. This will not only determine the next label to be rotated and shaded, but also determine when the second sub-process of the animation effect (scaled-up) should begin.


Now deal with the first part of the animation effect. This function is fully implemented using a function called ANIMATEREFRESHSTEP1 ():


}


Let's talk about the core of the above code. Initially, the ISANIMATING flag is set to true, so there is no animation process to start. You will then see the judging process. Next, you'll notice that there are two blocks of code that produce an animated effect. The second block of code begins when the first block of code executes. The reasons for this are two points:


We perform the rotation of the current label and change the color of the label text in the first block of code (see the description of the Currentlabelindex property). At the end of the child process of the animation effect, to restore the state of the label, the process should be graceful and gentle, rather than appearing abrupt and unnatural. Obviously, the second paragraph plays a role in the animation effect of the code block.


Within the code block that produces the animation effect, completion handler (completion handler) checks to see if the Currentlabelindex property value is valid. If valid, the same function is called again and again. This makes the next tag an animated effect. In addition, after all the labels have performed the animation process, the custom method (AnimateRefreshStep2 ()) of the second sub-procedure of the animation process is called.


You must have noticed the Getnextcolor () function (in the first animation effect code block). As I said before, this function gets the text color of the current animated control. Look at this part for a while.


We now resolve the second sub-process of animation effect, implementing the ANIMATEREFRESHSTEP2 () function:



We have used two blocks of code that produce animation effects. In the first block of code, all the labels are magnified in equal proportions. Note that there is no way to complete a task using a looping structure (for example, a for statement). The execution of the loop structure is independent of the animation process, so that the loop structure is completed long before all the labels are scaled up and executed.


After the program executes the "Finish Processing" section, all of the tags have completed initialization processing. As a result, these labels return to their original state once again. The "Finish processing" section inside the animation effect code block uses the IF statement, and the refresh process is still in progress, and we're ready to start the whole animation again. This task can be accomplished by simply setting the initial value (0) for the Currentlabelindex property and invoking the first custom method to perform the animation. Next we'll deal with what happens after the refresh is over. However, if the refresh is finished, you can modify the ISANIMATING flag to indicate that no more animations are performed, and to participate in the animation process by assigning an initial value to all attributes (and views). In this way, the animation process will start again the next time the table view is pulled.


The question comes out, where should the custom animation begin? If you look closely at the animation above, you will find that each time the table view is dragged, the animation starts once. From a programmatic standpoint, a table view is a scrolling view (scroll


View), the proxy method We care about is scrollviewdidenddecelerating (_:). This method is called every time that the table view is scrolled off. This method will initially check whether the refresh process is in progress. In our case, we're going to check the value of the isanimating flag. If no animation is in progress, the first function implemented before the initialization is called. Just like the following code:

It is important to note that the use of the above scrolling view proxy method is not mandatory, depending on the code logic of the custom Pull-to-refresh control. You can also consider other proxy methods, such as Scrollviewdidscroll (_:).


Still a part of it doesn't say, that's the implementation of the Getnextcolor () function:

}


It's very simple! First put some predefined colors (in order completely random) into the array. Then confirm the value of the Currentcolorindex property. If you do not have a valid value, you must assign the initial (0). Use Currentcolorindex to represent a color and then accumulate its value, so you won't get the same color again when you Getnextcolor () again. The function finally returns the selected color.


You can now try running the app again. When you drag and refresh, you see an animated effect. Of course, refreshing the control does not go away. This part has not yet been fulfilled. Whatever you do, any part of the animation can be modified.


Things outside of custom animations


Creating custom animations for Pull-to-refresh controls is fun, but don't forget that user refresh is not light in order to see how well the controls look, users need to get new content. This is also your main idea when customizing the Pull-to-refresh control. As a result, the next step is to implement the process of truly acquiring data after you have completed these things.


Obviously, this article does not cover the operation of getting any data, nor does it update the contents of the table view. However, none of this prevents us from implementing the logic described earlier. So to continue the rest of the task, it is to create a new custom function, called dosomething () (Pretty funny name, is not think is a function of what can not do). We're going to initialize a timer (Nstimer) object in the function. After a 4-second interval, a signal for the end of the refresh process is emitted. There is no need to do this in real-world applications. When the process to get the data ends, the refresh process ends.


First, go back to the beginning of the class definition, and (the last time) declare an object:


4 seconds is enough, so you can see the animation more than once. In the method above, you can see the only line of code that is called after the preset interval Endofword (). This will stop the refresh process and invalidate the timer:



We are almost done at this time. The only thing to do is call the DoSomething () function, which is called before the animation process begins. Therefore, you need to modify the proxy method of the scrolling view again:


Sample program is done, this time again experience!


Summarize


As you can see, customizing a Pull-to-refresh control is not a bit difficult. It's just a graphic representation of good ideas, that's all. As I said in the last section, the main thrust is the acquisition of real data rather than showing off the visualizations created. Also note that once the data has been updated, do not worry about extending the time to prevent the refresh control hidden. Doing so can lead to a bad user experience that you don't want to see.


If the application is very helpful to the user, there will be many opportunities for users to appreciate the customization of the software, so do not attempt to update it and also prevent the refresh control from being hidden. The custom content of the sample program in this article is relatively simple but sufficient to illustrate the problem. You know, it's a programming problem, you can accept a lot of custom content and improvisation. Of course, the final application may even be different from each other. The custom Pull-to-refresh control needs to match the different apps. In short, this article to the end, I sincerely hope that you will be helpful. can help you to happily develop custom Pull-to-refresh controls!


Customizing the Pull to refresh control using the Swift language

Related Article

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.