"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 also need to be defined to correspond to Iboutlet and ibaction to facilitate the use of them.

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 add    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, infer 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    [self addoptionbtn:question];}

Of course, in Viewload, to have the view display the first page, you need to include 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 the correct answer//delete the previous question of the answer//Let all objects in the array run the same way. Replace the following for loop with this sentence [Self.answerView.subviews makeobjectsperformselector: @selector (Removefromsuperview)];//for ( UIView *subviews in Self.answerView.subviews) {//[subviews removefromsuperview];//}//Then add new answer, depending on the length of the answer    to join int length=question.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 answer button text corresponding button display, with for traversal    //Get button text with currenttitle//    nsstring *answertitle=[answerbtn Titleforstate:uicontrolstatenormal];    For (UIButton *optionbtn in self.optionView.subviews) {//        nsstring *optiontitle=[optionbtn titleforstate: UIControlStateNormal];        Infer which OptionButton to show again. And the button itself is hidden, because option may have the same text        if ([Answerbtn.currenttitle IsEqualToString:optionBtn.currentTitle] & & Optionbtn.hidden==yes) {            optionbtn.hidden=no;            break;        }    }    Click on the button text disappears, because the text above need to use the comparison, so more late, and then remove the text    [answerbtn settitle:nil forstate:uicontrolstatenormal];        Click on a button at random. Equivalent to the removal of 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//also first delete and add, same as replace 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, clicked Button disappears optionbtn.hidden=yes;//cannot be deleted, because also to display, so with hide//2, display text to correct answer Go up (the first without the text of the Answerbutton)//Set up here, can not see the effect, is due to the answer text is white by default, in the background of the same for (UIButton *answerbtn in Self.answerView.subviews        ) {//infer 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}}/per click a OptionButton to infer whether the answer has been filled, and to infer whether 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];        }}//Assuming the answer is full, then infer 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]; }//Infer right after//get current points first, 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 run: Skip to next topic//direct with [self nextquestion]; jump right away [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) corresponding, 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 Answer button. is equivalent to 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. Infer 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 to adjust the order of the images. And let animations such as pictures and shadows change

-(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]; Same.        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. For example, the following:

-(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 infer if 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 talent 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);//can also record the original position before getting bigger//    [UIView commitanimations];} -(void) removecover{//    [self.cover removefromsuperview];//    self.cover=nil;//easy to infer 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) {}]; Assume that there is no code that needs to run after the animation is complete. Then the completion can be removed from the back.

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

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

--assuming that the frame property setting for the picture does not take effect, that is, it does not zoom out and move. Then usually auto layout is not closed.

--button has a default property: When pressed, the color dims, assuming no need, uncheck "highlighted adjusts Image".

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

--To achieve transparency, is the attribute alpha.

--To remove a control in general, you need to call the Removefromsuperview method on the control itself.

But suppose you want to delete very many sub-views inside a view, in addition to using a for loop to make the child view self-deleting itself, you can also use the following method: Makeobjectsperformselector.

    [Self.answerView.subviews makeobjectsperformselector: @selector (Removefromsuperview)];//for    (UIView *subviews In self.answerView.subviews) {//        [Subviews removefromsuperview];//    }
--In general, we assume that you delete a control and, after deletion, set the control to nil. And do not want to delete. The hidden property of the control is used only to hide it and then to display it later.

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

--Infer that the button has no text: infer whether the length of the button text equals 0.

--appendstring method for adding variable strings.

--delay running an action can be used Performselector: @selector () Withobject:nil Afterdelay: This method.

Assume that [self perform ...] So that's the way to delay running self in selector.

--Converts a string into an integer that 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 picture size and naming conventions directly as required. and drag it to Image.xcassets's AppIcon.


(10) How to join the launch page?

Set directly inside the launchscreen.xib. This is like playing storyboard.

The size we set here is 3.5inch. So after setting the device size. Remove the original, and get a imageview straight away. Add a picture on top to do 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.