iOS Development Tips Series---use chained programming and block for Uialertview

Source: Internet
Author: User

Uialertview is one of the most commonly used controls in the iOS development process and is the most important tool to remind users to make choices. In IOS8 and later systems, Apple recommends using Uialertcontroller instead of Uialertview. So this article does not encourage developers to use Uialertview,
The purpose of this article is to explore how to change the original assignment of variables into a chain-based programming style and back-to-back through the block. By learning how to transform Uialertview, you can learn this more convenient way to develop your iOS developers.


What is chained programming

For developers with a certain development experience, chained programming is no stranger. There are many well-known open source libraries that use this style of programming, such as the famous jquery, while iOS libraries, masory and Snapkit are typical examples of using chained programming.
In general, chained programming is the operation of multiple operations (multiple lines of code) through some type of operator (usually the dot number). Link the code into one sentence. The code is more compact, more readable, and reduces the repetition of the code. For example, the following code:

 1  //  2  txtusername.placeholder =  "    "  3  Txtusername.font = Uifont.systemfont (15  )   Uicolor.graycolor ()  5  //  statement using chained programming  6  Txtusername.setplaceholder (  "  ). SetFont (15 ). SetTextColor (Uicolor.graycolor ()) 

In this example, the reader should be able to understand more clearly what a chained programming style is. In short, the chain programming style should have the following characteristics

    • It is usually called a function to assign a value to a property. That is, the function encapsulates the assigned statement, and it can add its own judgment and some logic to it.
    • The function must have a return value, usually itself. It can also be a processed data or object.
    • You can use a static function as the starting function, but all of the following are instance functions.
    • You can set a final function that does not return any objects, using it to completely last all operations.
The pros and cons of chained programming

The main advantage of using chained programming is that you can make your code more concise and write a "refreshing" feeling. Design excellent chain programming can greatly reduce the duplication of code, enhance the sense of logic. The disadvantage is the folio
The business logic capability of the sender is high, and because chained programming is called function, it is possible to create too deep a function call stack. Slightly affect performance.

Use block to back-tune Uialertview delegate

Many of the callbacks in iOS development are done using delegate, and I'm sure you've written it many times. Relatively speaking, the use of delegate is more cumbersome, and sometimes need to be in the delegate
Judging which object is delegate, the advantage is that the operation is more efficient. Instead, blocks are more intuitive to write and more efficient to develop. Apple is also gradually using block instead of Delegate,ios.
8 The most recent action in Uiviewcontroller has been implemented using blocks. And in Swift's closures, anonymous functions abound. So boldly use block instead
Delegate and Target-action, Apple will help us deal with all kinds of performance problems. However, it is necessary to pay attention to the problem of retian-circle, the first knowledge of block is very easy to see this problem.

Use chained programming and block to transform Uialertview

There are two ways to change the Uialertview delegate to Block's callback, one is to use the runtime to Uialertview with the Block property. Second, write a new class inheritance
Uialertview, this article uses the second approach, which is easier to write.

Define a new class to inherit the Uialertview, and implement the Uialertviewdelegate protocol
1 classblockalert:uialertview,uialertviewdelegate{2var completion: ((Buttonindex:int,alert:uialertview)->void)?//define each block to be used as a callback, whose parameter name and the delegate callback function parameter names one to3var Willdismissblock: ((Buttonindex:int,alert:uialertview)->void)?4var Diddismissblock: ((Buttonindex:int,alert:uialertview)->void)?5var Didpresentblock: ((Alert:uialertview)->void)?6var Willpresentblock: ((Alert:uialertview)->void)?7var Alertwithcancelblock: ((Alert:uialertview)->void)?8     OverrideInit (frame:cgrect) {9 super.init (frame:frame)TenSelf.Delegate= Self//set delegate as your own One     } A func Alertview (Alertview:uialertview, Clickedbuttonatindex buttonindex:int) { -         ifLet block = completion{//The main block, when the user clicked the button callback, the first to determine the existence of this block? - block (Buttonindex:buttonindex, Alert:alertview) the         } -     } - func Alertview (Alertview:uialertview, Diddismisswithbuttonindex buttonindex:int) { -         ifLet block = diddismissblock{//the other calls each block in turn according to the corresponding delegate callback function + block (Buttonindex:buttonindex, Alert:alertview) -         } +     } A func Alertview (Alertview:uialertview, Willdismisswithbuttonindex buttonindex:int) { at         ifLet block =willdismissblock{ - block (Buttonindex:buttonindex, Alert:alertview) -         }    -     } -     //several other delegate methods have also been omitted, the principle is the same -Required init?(coder Adecoder:nscoder) { inFatalError ("Init (coder:) has not been implemented") -     } to}

Referring to the above code, the general idea is to set the delegate to itself in the constructor, and then all the functions inside the delegate are implemented with blocks, the parameters of the block and the function parameters of the delegate callback. When there is a delegate function callback, first judge this
Block is nil, if not, execute the block
The next step is easy.

Extend the Uialertview directly, plus the chained programming functions you want
1 extension Uialertview {2     StaticFunc setmessage (msg:string)->uialertview{//Here you set this as a static function, instantiate a Blockalert object inside, and then return the object3Let alert =Blockalert ()4Alert.message =msg5         returnAlert6     }7 8Func Addalertstyle (Style:uialertviewstyle)->uialertview{//encapsulate some operations directly in each function. and return to itself.9Self.alertviewstyle =styleTen         return Self One     } A  -Func AddTitle (title:string)uialertview{ -Self.title =title the         return Self -     } -  -Func Addfirstbutton (btntitle:string)uialertview{ + self.addbuttonwithtitle (btntitle) -         return Self +     } A  atFunc Addsecondbutton (btntitle:string)uialertview{ - self.addbuttonwithtitle (btntitle) -         return Self -     } -  -Func addbuttons (btntitles:[string])uialertview{ in          forTitleinchbtntitles{ - Self.addbuttonwithtitle (title) to         } +         return Self -     } the  *Func addbuttonclickevent (Clickbutton: ((Buttonindex:int,alert:uialertview)->void)?) -uialertview{ $         ifLet alert = self as? blockalert{//for block, it is the first to determine whether it is blockalert, if it is to add the block, followed by this operationPanax NotoginsengAlert.completion =Clickbutton -         } the         return Self +     } A  the     //part of the function is omitted, because the principle is the same. +Func addalertcancelevent (Event:((Alert:uialertview)->void)?) -uialertview{ -         ifLet alert = self as?blockalert{ $Alert.alertwithcancelblock =Event $         } -         return Self -     } the  - WuyiFunc Alertwithbuttonclick (Clickbutton: ((Buttonindex:int,alert:uialertview)->void)?){ the         ifLet alert = self as? blockalert{//This is the terminating function, there is no return value, and the show () method is called directly inside. -Alert.completion =Clickbutton Wu alert.show () -         } About     } $}

In this case I chose to use Uialverview to expand, not Blockalert, which could lead to pitfalls in development. Because the object returned in the first static function is a Blockaction object, not a Uialertview object
When adding a block at the end of the first to determine whether it is a Blockaction object, if it is then set block, so in the development process to be careful of this trap. Of course, readers can also expand the Blockalert directly, which is safer.

Finally, a static function plus chained programming is used to eject alert
Uialertview.setmessage ("here to set the information"). AddTitle ("I am the title"). Addfirstbutton ("Cancel"). Addsecondbutton ("Confirm"). Alertwithbuttonclick {(buttonindex, alert), VoidinchPrint ("you pressed the Buttonindex button.")            //you pressed the 1th button.//you pressed the No. 0 button.}

It's also easy to use a different delegate method

1Uialertview.setmessage ("here to set the information"). AddTitle ("I am the title"). Addfirstbutton ("Cancel"). Addsecondbutton ("Confirm"). Addwillpresentevent {(alert)inch2Print"The Alertview would present")3}.adddidpresentevent {(alert)inch4Print"The Alertview did present")5}.alertwithbuttonclick {(Buttonindex, alert)inch6Print"you pressed the Buttonindex button.")7}

Of course, some other custom style, or with the user name input and password input box is also very simple

1Uialertview.setmessage ("here to set the information"). AddTitle ("I am the title"). Addfirstbutton ("Cancel"). Addsecondbutton ("Confirm"). Addalertstyle (. Loginandpasswordinput). adddidpresentevent {(alert)inch2Print"The Alertview did present")3}.alertwithbuttonclick {(Buttonindex, alert)inch4Let txt1 = Alert.textfieldatindex (0)?. Text5Let txt2 = Alert.textfieldatindex (1)?. Text6Print"username:\ (TXT1) password:\ (TXT2)")7             //print out the Alertview did present8             //username:optional ("111") password:optional ("222" )9}

Alert with user name password

It can be seen that the use of chained programming block is basically just a few lines of code to meet most of the use of uialertview use of the scene, writing it is very convenient and fast. For Uiactionsheet, too, It can be completely transformed into using chained programming and block. This is left to the reader.
To finish. Believe that reading the above code and practice of the reader will soon be able to write. All of the above code can be seen on my GitHub duckdeck-grandcue
But Apple is still recommending developers to use the latest Uialertcontroller, and its API design and Uialertview are completely different. Changed to block-based callback, which is more convenient to use. Here This article gives you a detailed introduction to
Uialertcontroller detailed, interested readers can go to see

Summarize

This article uses a simple enough example to discuss how to use the Uialertview programming method to change the programming method based on the chain programming and block. But in the actual development process, the situation is much more complicated than this, first of all to consider the business and logic suitable for using chained programming, Second, the design of a good
The chained programming API also takes a lot of effort. The design of the function return value is also very useful because it directly affects the next calling function.

iOS Development Tips Series---use chained programming and block for Uialertview

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.