"iOS Dev-51" case study: New animation, delete sub-view, view order, delay method, button multifunction usage and icon icon and start Page settings

Source: Internet
Author: User

Case Effect:



(1) Import the required material, and then use storyboard to put the upper half position and the size of the relatively fixed things up. Of course, these controls are also defined as corresponding Iboutlet and ibaction to facilitate subsequent use.

Note: This case is best displayed on a 3.5inch device, so you need to set it up.


(2) First realize the function of clicking "Next Question"

-(Ibaction) nextquestion {    //1, serial number increase    self.index++;    2, according to the serial number to get the corresponding model (object)    nsquestion *question=self.questions[self.index];    3, set the text and image    self.nolabel.text=[nsstring stringwithformat:@ "%d/%d", Self.index+1,self.questions.count];    Self.titlelabel.text=question.title;    [Self.iconbtn setimage:[uiimage ImageNamed:question.icon] forstate:uicontrolstatenormal];    4, Judge whether the button is invalid    self.nextquestionbtn.enabled=self.index!= (self.questions.count-1);    5. Add the correct answer    [self addanswerbtn:question];    6. Add option option    [self addoptionbtn:question];}

Of course, in viewload to have the view display the first page, you need the following:

-(void) viewdidload {    self.index=-1;    [Self nextquestion];    [Super Viewdidload];}

Then implement each of the methods mentioned in the Nextquestion method.

(3) Define a data model class that transforms a dictionary into a model

In the NSQuestion.h:

#import <Foundation/Foundation.h> @interface nsquestion:nsobject@property (nonatomic,copy) NSString *answer;@ Property (nonatomic,copy) NSString *title; @property (nonatomic,copy) nsstring *icon; @property (Nonatomic,strong) Nsarray *options;-(Instancetype) Initwithdic: (Nsdictionary *) dict;+ (instancetype) Questionwithdic: (NSDictionary *) Dict; @end

In the NSQUESTION.M:

#import "NSQuestion.h" @implementation nsquestion-(Instancetype) Initwithdic: (nsdictionary *) dict{    if ([super Init]) {        self.answer=dict[@ "answer"];        self.title=dict[@ "title"];        self.icon=dict[@ "icon"];        self.options=dict[@ "Options"];    }    return self;} + (Instancetype) Questionwithdic: (nsdictionary *) dict{    return [[Self alloc]initwithdic:dict];} @end


Transform into a model in VIEWCONTROLLER.M:

#import "ViewController.h" #import "NSQuestion.h" @interface Viewcontroller () @property (nonatomic,strong) Nsarray * Questions, @end @implementation viewcontroller-(Nsarray *) questions{    if (_questions==nil) {        Nsarray *arr1=[ Nsarray arraywithcontentsoffile:[[nsbundle mainbundle]pathforresource:@ "Questions.plist" ofType:nil];        Nsmutablearray *questionarray=[[nsmutablearray Alloc]init];        For (Nsdictionary *dic1 in arr1) {            nsquestion *question=[[nsquestion alloc]initwithdic:dic1];            [Questionarray addobject:question];        }        _questions=questionarray;    }    return _questions;}

(4) Addanswerbtn method

-(void) ADDANSWERBTN: (nsquestion *) question{//5, add correct answer//Remove previous question answer//Let all objects in the array execute the same method, replace the following for loop with this sentence [s Elf.answerView.subviews makeobjectsperformselector: @selector (Removefromsuperview)];//for (UIView *subviews in Self.answerView.subviews) {//[subviews removefromsuperview];//}//And then add a new answer, based on the length of the answer to add int length=qu    Estion.answer.length;        for (int i=0; i<length; i++) {UIButton *answerbtn=[[uibutton alloc]init]; [Answerbtn Settitlecolor:[uicolor Blackcolor] forstate:uicontrolstatenormal];//Set text color, otherwise the default white is the same as the background [answerbtn SetBac        Kgroundimage:[uiimage imagenamed:@ "Btn_answer"] forstate:uicontrolstatenormal];        [Answerbtn setbackgroundimage:[uiimage imagenamed:@ "btn_answer_highlighted"] forstate:uicontrolstatehighlighted];        CGFloat answermargin=10;        CGFloat answerw=35;        CGFloat answerh=35; CGFloat answerx= (self.view.frame.size.width-length*answerw-(length-1) *answermargin)/2+i* (answerW+answerMargin);        Answerbtn.frame=cgrectmake (Answerx, 0, Answerw, answerh);                [Self.answerview ADDSUBVIEW:ANSWERBTN];    Listen for click events [answerbtn addtarget:self action: @selector (Answerclick:) forcontrolevents:uicontroleventtouchupinside]; }}

The method of this click event:

-(void) Answerclick: (UIButton *) answerbtn{    //Let the buttons for the answer button text appear, use for traversal    //Get button text with currenttitle//    NSString *answertitle=[answerbtn Titleforstate:uicontrolstatenormal];    For (UIButton *optionbtn in self.optionView.subviews) {//        nsstring *optiontitle=[optionbtn titleforstate: UIControlStateNormal];        Determine which option button is displayed again, and the button itself is hidden, because option may have the same text        if ([Answerbtn.currenttitle isequaltostring:o Ptionbtn.currenttitle] && optionbtn.hidden==yes) {            optionbtn.hidden=no;            break;        }    }    Click the button text disappears, because the text above need to compare, so later, then the text removed    [answerbtn settitle:nil forstate:uicontrolstatenormal];        Click any button, equivalent to remove text, then the answer is not the correct answer, the text color reply black for    (UIButton *answerbtn in self.answerView.subviews) {        [ ANSWERBTN Settitlecolor:[uicolor Blackcolor] forstate:uicontrolstatenormal];}    }

(4) Addoptionbtn method

-(void) ADDOPTIONBTN: (nsquestion *) question{//6, add option option//also delete and add again, also use a sentence instead of for loop [Self.optionView.subviews make        Objectsperformselector: @selector (Removefromsuperview)];//for (UIView *subviews in self.optionView.subviews) {//    [Subviews removefromsuperview];//} int count=question.options.count;    int totalcolumn=7;        for (int i=0; i<count; i++) {UIButton *optionbtn=[[uibutton alloc]init];        [Optionbtn setbackgroundimage:[uiimage imagenamed:@ "btn_option"] forstate:uicontrolstatenormal];        [Optionbtn setbackgroundimage:[uiimage imagenamed:@ "btn_option_highlighted"] forstate:uicontrolstatehighlighted];        CGFloat optionmargin=10;        CGFloat optionw=35;        CGFloat optionh=35;        int ROW=I/7;        int col=i%7; CGFloat optionx= (self.view.frame.size.width-totalcolumn*optionw-(totalColumn-1) *optionmargin)/2+col* (optionW+        Optionmargin);        CGFloat optiony=row* (Optionh+optionmargin); Optionbtn.frame=cgrectmake (optIonx, Optiony, Optionw, Optionh);        [Optionbtn Settitle:question.options[i] forstate:uicontrolstatenormal];        [Optionbtn Settitlecolor:[uicolor Blackcolor] forstate:uicontrolstatenormal];                [Self.optionview ADDSUBVIEW:OPTIONBTN];    button click [Optionbtn addtarget:self Action: @selector (Optionclick:) forcontrolevents:uicontroleventtouchupinside]; }}

This listener event method:

-(void) Optionclick: (UIButton *) optionbtn{//1, click the button disappears optionbtn.hidden=yes;//cannot be deleted, because also to display, so with hide//2, display text to the correct answer up (No.        A answer button without text)//Set up here, can not see the effect, is because the answer text default is white, the same background for the (UIButton *answerbtn in self.answerView.subviews) {        Determine if there is text//NSString *answertitle=[answerbtn Titleforstate:uicontrolstatenormal]; if (answerbtn.currenttitle.length==0) {[answerbtn settitle:[optionbtn Titleforstate:uicontrolstatenormal] ForS            Tate:uicontrolstatenormal];    break;//to notify for traversal}}//Click an option button to determine if the answer has been filled and to determine if the correct BOOL full=yes;    Nsmutablestring *tempanswertitle=[nsmutablestring string]; For (UIButton *answerbtn in self.answerView.subviews) {//NSString *answertitle=[answerbtn Titleforstate:uicontrolst        Atenormal];        if (answerbtn.currenttitle.length==0) {//description answer is not full full=no;   }//Splicing text if (answerbtn.currenttitle) {[Tempanswertitle appendString:answerBtn.currentTitle];     }}//If the answer is full, determine if the correct if (fully) {nsquestion *question=self.questions[self.index]; if ([Tempanswertitle IsEqualToString:question.answer]) {for (UIButton *answerbtn in Self.answerView.subviews)            {[answerbtn settitlecolor:[uicolor bluecolor] forstate:uicontrolstatenormal]; }//correct after//get current points, add points [self addscore:100];//int score=[self.scorebtn Titlefo rstate:uicontrolstatenormal].intvalue;//score+=100;//[self.scorebtn settitle:[nsstring StringWithF            ormat:@ "%d", score] forstate:uicontrolstatenormal]; Deferred execution: Jumps to the next question//directly with [self nextquestion]; jumps immediately [self performselector: @selector (nextquestion) withobject        : Nil afterdelay:0.5];  }else{for (UIButton *answerbtn in self.answerView.subviews) {[Answerbtn Settitlecolor:[uicolor            Redcolor] Forstate:uicontrolstatenormal]; }        }    }}

Here is a way to calculate fractions using a addscore:

-(void) Addscore: (int) dealtscore{    int score=[self.scorebtn titleforstate:uicontrolstatenormal].intvalue;    Score+=dealtscore;    [Self.scorebtn settitle:[nsstring stringwithformat:@ "%d", score] forstate:uicontrolstatenormal];}

(5) Accordingly, click "Hint" to produce the effect, is to empty the answer, give the first word, and deduct points

-(ibaction) Tip {    //1, first empty answer, that is, click the Answer button, the equivalent of emptying for    (UIButton *answerbtn in self.answerView.subviews) {        [self answerclick:answerbtn];    }    2, take out the correct answer    nsquestion *question=self.questions[self.index];    3. Remove the first character of the correct answer    NSString *firstanswer=[question.answer substringtoindex:1];    4. Judge and remove the for    (UIButton *optionbtn in self.optionView.subviews) {        if ([optionbtn.currenttitle) from option. Isequaltostring:firstanswer]) {            [self optionclick:optionbtn];            break;        }    }    5. Deduction Points    [self addscore:-500];//    int score=[self.scorebtn titleforstate:uicontrolstatenormal].intvalue;//    score-=500;//    [Self.scorebtn settitle:[nsstring stringwithformat:@ "%d", score] forstate:uicontrolstatenormal];}

(6) Click on the "big picture" effect, add a shadow, adjust the image order, and let the pictures and shadows and other animation changes

-(Ibaction) bigimg {//1, add a translucent shadow UIButton *cover=[[uibutton alloc]init];    Cover.frame=self.view.bounds;    Cover.backgroundcolor=[uicolor Blackcolor];    cover.alpha=0;    [Cover addtarget:self action: @selector (SMALLIMG) forcontrolevents:uicontroleventtouchupinside];    Self.cover=cover;        [Self.view Addsubview:cover];        2. Adjust shadow and image order [Self.view BringSubviewToFront:self.iconBtn];         Similarly, use block to modify the following code [UIView animatewithduration:0.5 animations:^{cover.alpha=0.7;//shadows appear gradually//3, change the image size frame        CGFloat iconw=self.view.frame.size.width;        CGFloat iconh=iconw;        CGFloat icony= (SELF.VIEW.FRAME.SIZE.HEIGHT-ICONH)/2;    Self.iconbtn.frame=cgrectmake (0, Icony, iconw, Iconh);    }]; [UIView beginanimations:nil context:nil];//cover.alpha=0.7;//Shadow appears gradually////3, change image size frame//cgfloat iconw=self . view.frame.size.width;//cgfloat iconh=iconw;//cgfloat icony= (self.view.frame.size.height-iconh)/2;//Self.icon Btn.frame=cGrectmake (0, Icony, iconw, ICONH);//[UIView commitanimations];} 

In the above code, the shadow cover has an event, that is, after clicking the image to restore the small image, and the shadow disappears, and so on, as follows:

-(void) smallimg{    //Use block animation to transform the following code and Removecover method    [UIView animatewithduration:0.5 animations:^{        self.cover.alpha=0;//first let the shadows fade away, then delete self.iconbtn.frame=cgrectmake (------        ),    completion:^ (BOOL Finished) {        [self.cover Removefromsuperview];        self.cover=nil;//easy to judge whether the shadow still exists    }];    ///1, delete shadow////    //2, image position recovery frame//    [UIView beginanimations:nil context:nil];//    //animation ends, Call the Removecover method of self to delete the shadow, so that there is a delay in removing the shadow, the shadow fades out of the animation to normal//    [UIView setanimationdelegate:self];//    [UIView Setanimationdidstopselector: @selector (removecover)];//    self.cover.alpha=0;//Let the shadows fade away, then delete//    Self.iconbtn.frame=cgrectmake (85, 86, 150, 150);//You can also record the original position before it becomes larger//    [UIView commitanimations];} -(void) removecover{//    [self.cover removefromsuperview];//    self.cover=nil;//Easy to determine if the shadow still exists//}

(7) When you click on the image itself, there will be a zoomed-out event:

-(Ibaction) Iconclick {    if (self.cover==nil) {        [self bigimg];    } else{        [self smallimg];}    }

(8) The knowledge points used

--Gets the current text of the button with the. Currenttitle property.

--To achieve animation effects, in addition to [UIView Beginanimations:] This set of combinations, we recommend the use of [UIView animatewithduration:animations:^{} completion:^ (BOOL Finished) {}]; if there is no code that needs to be executed after the animation is complete, then the completion can be removed.

--Adjust Sub-view stacking order can be used Bringsubviewtofront methods.

Note that the text of the button is white by default, and if the background is white, you need to pay extra attention.

--If the frame property setting of the picture does not take effect, that is, it does not zoom in and out of the mobile effect, then generally auto layout is not closed.

--the button has a default property: The color is dimmed when pressed, and if not, uncheck "highlighted adjusts Image".

--The first few characters of a string are truncated with Substringtoindex, the number is n, and the characters are 0~n-1.

--To achieve transparency, is the attribute alpha.

--typically to delete a control, you need the control to call the Removefromsuperview method itself. But if you want to delete many of the views inside a view, in addition to using a for loop to make the child view self-deletion, you can also use the following methods: Makeobjectsperformselector,

    [Self.answerView.subviews makeobjectsperformselector: @selector (Removefromsuperview)];//for    (UIView *subviews In self.answerView.subviews) {//        [Subviews removefromsuperview];//    }
--In general, if we delete a control, after deleting it, set the control to nil. Instead of deleting it, just hide it, and then you need to show it again, then use the hidden property of the control.

-Note the code order. For example, the button on the text and other buttons on the comparison of the text, and then delete this button, this is the correct order, and can not be deleted first, otherwise you cannot get the text on this button.

--Determines whether the button text is equal to the length of 0.

--appendstring method for adding variable strings.

--delaying execution of an action can be done with Performselector: @selector () Withobject:nil Afterdelay: This method. If it is [self perform ...] Then there is the way to defer execution of Self's selector.

--Converts a string into an integer, which can be added directly after the string. Intvalue property.


(9) How to add icon icons (iphone, AppStore and Spotlight, and of course, ipad, etc.)

Define the image size and naming specification directly as required, then drag it to the Image.xcassets AppIcon.


(10) How do I add a startup page?

Directly in the launchscreen.xib inside the set, this and play storyboard the same kind.

We set the size here is 3.5inch, so set the device size, the original deleted, directly to a imageview, add a picture on it.


"iOS Dev-51" case study: New animation, delete sub-view, view order, delay method, button multifunction usage and icon icon and start Page settings

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.