An example _ios for IOS to realize the electric merchant shopping Cart Interface

Source: Internet
Author: User
Tags uikit

First look at the interface Effect diagram:

The main realization of the display of goods , and can be more selective operation of goods, and change the number of purchases of goods . At the same time, calculate the total price selected.


To do this type of project: Note that the view is separated from the data. The view's presentation source is the data model layer. So what I do is to change the content of the data layer, to update the view interface according to the data content.
has been under the specific implementation of ideas and code:

1. Implementation steps

    1. Include the ViewController.h header file in the APPDELEGATE.M, create the Viewcontroller object (VC), and then create a Uinavigationcontroller object (NVC) to set the VC to its own root view, Finally, the Self.window.rootViewController is set to NVC.
    2. Create a globally variable array in VIEWCONTROLLER.M and add the data dictionary objects that the table requires to it.
    3. Create a Goodsinfomodel class that inherits from the NSObject class and is used to do the data model
    4. Create a Mycustomcell class that inherits from UITableViewCell, custom cell classes
    5. In the MYCUSTOMCELL.M class, implement the layout of the cell
    6. Create a table view in VIEWCONTROLLER.M and create a table-tail view
    7. The Mycustomcell class defines the protocol, implements the proxy, completes the addition and subtraction operation.
    8. The VIEWCONTROLLER.M is implemented in a full selection operation.

2. Code implementation

2.1 Completing the navigation bar creation of the interface

Include the ViewController.h header file in the APPDELEGATE.M, create the Viewcontroller object (VC), and then create a Uinavigationcontroller object (NVC) to set the VC to its own root view, Finally, the Self.window.rootViewController is set to NVC.

2.1.1 Code

In APPDELEGATE.M-(BOOL) Application: (uiapplication) Application didfinishlaunchingwithoptions: (NSDictionary) The following code is implemented in the Launchoptions method (remember to include #import "ViewController.h"):

 Create window
Self.window = [[UIWindow alloc]initwithframe:[uiscreen mainscreen].bounds];
Self.window.backgroundColor = [Uicolor whitecolor];

Create a navigation controller that becomes the root view

uinavigationcontroller *nav = [[Uinavigationcontroller alloc]initwithrootviewcontroller:[ Viewcontroller New]];
Self.window.rootViewController = nav;

Display window
[Self.window makekeyandvisible];

Set in VIEWCONTROLLER.M's viewdidload, navigation bar title

 Self.title = @ "Shopping cart";
 Set the property style of the caption, etc.
[Self.navigationController.navigationBar settitletextattributes:@{ Nsforegroundcolorattributename: [Uicolor blackcolor],nsfontattributename:[uifont systemFontOfSize:23.0f]}];

2.2 Creating a model class for storing data models
Create a Goodsinfomodel class that inherits from NSObject
The implementation code is as follows: GoodsInfoModel.h

@interface goodsinfomodel:nsobject
@property (strong,nonatomic) nsstring *imagename;//merchandise picture
@property ( strong,nonatomic) nsstring *goodstitle;//product title
@property (strong,nonatomic) nsstring *goodsprice;//commodity price
@ Property (assign,nonatomic) BOOL selectstate;//Whether the state is selected
@property (assign,nonatomic) int goodsnum;//number of items

-( Instancetype) Initwithdict: (Nsdictionary *) dict;

@end
goodsinfomodel.m
-(Instancetype) Initwithdict: (nsdictionary *) dict
{
if (self = [super init] )
{
 self.imagename = dict[@ "imagename"];
 Self.goodstitle = dict[@ "Goodstitle"];
 Self.goodsprice = dict[@ "Goodsprice"];
 Self.goodsnum = [dict[@ "Goodsnum"]intvalue];
 Self.selectstate = [dict[@ "Selectstate"]boolvalue];

}

return self;

}

2.3 Creating data to set up tabular data

Create a globally variable array in VIEWCONTROLLER.M and add the data dictionary objects that the table requires to it.

2.3.1 Code

The

implements the following code in the VIEWCONTROLLER.M-(void) Viewdidload (first declare the Infoarr object in VIEWCONTROLLER.M). The code is as follows

@interface Viewcontroller () <UITableViewDataSource,UITableViewDelegate,MyCustomCellDelegate> {UITableView *_
 Mytableview;
 float Allprice;
Nsmutablearray *infoarr;
} @property (strong,nonatomic) UIButton *allselectbtn;

@property (strong,nonatomic) Uilabel *allpricelab;
@end---------------------------------------------------------------//initialization data Allprice = 0.0;

Infoarr = [[Nsmutablearray alloc]init]; /** * Initializes an array in which the dictionary is placed. The dictionary contains the data that the cell needs to display * * for (int i = 0; i<7; i++) {nsmutabledictionary *infodict = [[Nsmutabledictionary alloc]init]
 ;
 [Infodict setvalue:@ "Img6.png" forkey:@ "imagename"];
 [Infodict setvalue:@ "This is the commodity title" forkey:@ "Goodstitle"];
 [Infodict setvalue:@ "forkey:@" "Goodsprice"];
 [Infodict setvalue:[nsnumber Numberwithbool:no] forkey:@ "Selectstate"];


 [Infodict setvalue:[nsnumber numberwithint:1] forkey:@ "Goodsnum"];
 Encapsulating data Model Goodsinfomodel *goodsmodel = [[Goodsinfomodel alloc]initwithdict:infodict];

Put the data model into an array [Infoarr Addobject:goodsmodel];
}
 

2.4 Creating a Table View
The code is as follows:

/* CREATE TABLE and set proxy/
_mytableview = [[UITableView alloc]initwithframe:cgrectmake (0, 0, Self.view.frame.size.width, self.view.frame.size.height) Style:uitableviewstyleplain];
_mytableview.datasource = self;
_mytableview.delegate = self;

Add a tail view to the table

_mytableview.tablefooterview = [self creatfootview];

[Self.view Addsubview:_mytableview];

2.5 Creating a tail view

The code is as follows:

* * CREATE TABLE Tail View * @return Returns a UIView object view as a trailing view of the table/-(UIView *) creatfootview{UIView *footview = [[UIView ALLOC]INITWITHF
Rame:cgrectmake (0, 0, Self.view.frame.size.width, 150)];
Add a full text box label Uilabel *lab = [[Uilabel alloc]initwithframe:cgrectmake (self.view.frame.size.width-150, 10, 50, 30)];
Lab.text = @ "All selected";

[Footview Addsubview:lab];
Add Select all Picture button _allselectbtn = [UIButton buttonwithtype:uibuttontypecustom];
_allselectbtn.frame = CGRectMake (self.view.frame.size.width-100, 10, 30, 30);
[_allselectbtn setimage:[uiimage imagenamed:@ check box-unchecked '] forstate:uicontrolstatenormal];
[_allselectbtn addtarget:self Action: @selector (Selectbtnclick:) forcontrolevents:uicontroleventtouchupinside];

[Footview ADDSUBVIEW:_ALLSELECTBTN];
Add a summary text box Uilabel *lab2 = [[Uilabel alloc]initwithframe:cgrectmake (self.view.frame.size.width-150, 40, 60, 30)];
Lab2.textcolor = [Uicolor Redcolor];
Lab2.text = @ "Summary:";

[Footview ADDSUBVIEW:LAB2]; Add a Total Price text box to display the lump sum _allpricelab = [[Uilabel ALLOC]INITWITHFRAME:CGRectmake (self.view.frame.size.width-100, 40, 100, 30)];
_allpricelab.textcolor = [Uicolor Redcolor];
_allpricelab.text = @ "0.0";

[Footview Addsubview:_allpricelab];
Add a checkout button UIButton *settlementbtn = [UIButton buttonwithtype:uibuttontyperoundedrect];
[Settlementbtn settitle:@ "to settle" forstate:uicontrolstatenormal];
[Settlementbtn Settitlecolor:[uicolor Whitecolor] forstate:uicontrolstatenormal];
Settlementbtn.frame = CGRectMake (Ten, self.view.frame.size.width-20, 30);
Settlementbtn.backgroundcolor = [Uicolor Bluecolor];

[Footview ADDSUBVIEW:SETTLEMENTBTN];
return footview;
 }

2.6 Creates a custom cell class and implements the initialization method
creates a class named Mycustomcell inheritance UITableViewCell, Implement the overridden initialization method in MYCUSTOMCELL.M.
2.6.1 Code:
MyCustomCell.h:

#import <UIKit/UIKit.h> #import "GoodsInfoModel.h"//Add agent for the implementation of button addition and subtraction @protocol mycustomcelldelegate <nsobject

>-(void) Btnclick: (UITableViewCell *) cell Andflag: (int) flag; @end @interface Mycustomcell:uitableviewcell @property (strong,nonatomic) Uiimageview *goodsimgv;//Merchandise Pictures @property ( strong,nonatomic) Uilabel *goodstitlelab;//commodity title @property (strong,nonatomic) Uilabel *pricetitlelab;//price label @property ( strong,nonatomic) Uilabel *pricelab;//specific price @property (strong,nonatomic) uilabel *goodsnumlab;//Purchase quantity label @property ( strong,nonatomic) Uilabel *numcountlab;//number of purchases @property (strong,nonatomic) UIButton *addbtn;//Add the number of items @property ( strong,nonatomic) UIButton *deletebtn;//Delete the number of items @property (strong,nonatomic) UIButton *isselectbtn;//Whether the button is selected @property ( strong,nonatomic) Uiimageview *isselectimg;//whether to select a picture @property (assign,nonatomic) BOOL selectstate;//selected State @property (


assign,nonatomic) id<mycustomcelldelegate>delegate;
Assignment-(void) Addthevalue: (Goodsinfomodel *) Goodsmodel; MYCUSTOMCELL.M: First write a macro definition width.#define WIDTH ([UIScreen mainscreen].bounds.size.width)-(Instancetype) Initwithstyle: (Uitableviewcellstyle) style
 Reuseidentifier: (NSString *) Reuseidentifier {if (self = [super Initwithstyle:style Reuseidentifier:reuseidentifier]) {
 Layout interface UIView * Bgview = [[UIView alloc]initwithframe:cgrectmake (5, 5, WIDTH-10, 95)];
 Bgview.backgroundcolor = [Uicolor Whitecolor];
 Add product picture _GOODSIMGV = [[Uiimageview alloc]initwithframe:cgrectmake (5, 10, 80, 80)];
 _goodsimgv.backgroundcolor = [Uicolor Greencolor];
 [Bgview ADDSUBVIEW:_GOODSIMGV];
 Add Product Title _goodstitlelab = [[Uilabel alloc]initwithframe:cgrectmake (90, 5, 200, 30)];
 _goodstitlelab.text = @ "AFADSFA fa";
 _goodstitlelab.backgroundcolor = [Uicolor Clearcolor];
 [Bgview Addsubview:_goodstitlelab];
 Promotional Price _pricetitlelab = [[Uilabel alloc]initwithframe:cgrectmake (90, 35, 70, 30)];
 _pricetitlelab.text = @ "promotional Price:";
 _pricetitlelab.backgroundcolor = [Uicolor Clearcolor];
 [Bgview Addsubview:_pricetitlelab]; Commodity price _pricelab = [[Uilabel ALloc]initwithframe:cgrectmake (160, 35, 100, 30)];
 _pricelab.text = @ "1990";
 _pricelab.textcolor = [Uicolor Redcolor];
 [Bgview Addsubview:_pricelab];
 Purchase Quantity _goodsnumlab = [[Uilabel alloc]initwithframe:cgrectmake (90, 65, 90, 30)];
 _goodsnumlab.text = @ "Purchase quantity:";
 [Bgview Addsubview:_goodsnumlab];
 Minus button _deletebtn = [UIButton buttonwithtype:uibuttontypecustom];
 _deletebtn.frame = CGRectMake (180, 65, 30, 30);
 [_deletebtn setimage:[uiimage imagenamed:@ "button-.png"] forstate:uicontrolstatenormal];
 [_deletebtn addtarget:self Action: @selector (deletebtnaction:) forcontrolevents:uicontroleventtouchupinside];
 _deletebtn.tag = 11;
 [Bgview ADDSUBVIEW:_DELETEBTN];
 Number of items purchased _numcountlab = [[Uilabel alloc]initwithframe:cgrectmake (210, 65, 50, 30)];
 _numcountlab.textalignment = Nstextalignmentcenter;
 [Bgview Addsubview:_numcountlab];
 Add button _addbtn = [UIButton buttonwithtype:uibuttontypecustom];
 _addbtn.frame = CGRectMake (260, 65, 30, 30); [_addbtn setimage:[uiimage imagenamed:@ button +.PNG "] forstate:uicontrolstatenormal];
 [_addbtn addtarget:self Action: @selector (addbtnaction:) forcontrolevents:uicontroleventtouchupinside];
 _addbtn.tag = 12;
 [Bgview ADDSUBVIEW:_ADDBTN];
 Whether to select picture _isselectimg = [[Uiimageview alloc]initwithframe:cgrectmake (WIDTH-50, 10, 30, 30)];
 [Bgview addsubview:_isselectimg];

[Self addsubview:bgview];

return self; /** * Assign values to cells * @param goodsmodel inside the values required for each control--(void) Addthevalue: (Goodsinfomodel *) Goodsmodel {_goodsimgv.ima
GE = [UIImage imageNamed:goodsModel.imageName];
_goodstitlelab.text = Goodsmodel.goodstitle;
_pricelab.text = Goodsmodel.goodsprice;

_numcountlab.text = [NSString stringwithformat:@ "%d", goodsmodel.goodsnum];
 if (goodsmodel.selectstate) {_selectstate = YES;

_isselectimg.image = [uiimage imagenamed:@ check box-checked];
 }else{_selectstate = NO;

_isselectimg.image = [uiimage imagenamed:@ check box-unchecked]; }/** * Click minus button to achieve the reduction of the number * * @param sender minus button/(void) Deletebtnaction: (UIButton *) Sender {//Decide whether to select, select to click

if (_selectstate = YES) {//Invoke proxy [Self.delegate btnclick:self andflag: (int) Sender.tag]; /** * Click the Add button to achieve an increase in the number * * @param sender plus button/(void) Addbtnaction: (UIButton *) Sender {//Decide whether to select, select to click if (_selec
Tstate = YES) {//Invoke proxy [Self.delegate btnclick:self andflag: (int) Sender.tag];

 }


}

2.7 Proxy methods for implementing a table

Number of cells returned-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) Section {return
Infoarr.count;
 }//Custom cell contents-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) IndexPath {
 static NSString *identify = @ "Indentify";
 Mycustomcell *cell = [TableView dequeuereusablecellwithidentifier:identify];
 if (!cell) {cell = [[Mycustomcell alloc]initwithstyle:uitableviewcellstyledefault reuseidentifier:identify];
 Cell.delegate = self;
}//Call method, assign value to cell [cell Addthevalue:infoarr[indexpath.row]];
return cell; //Returns the height of the cell-(cgfloat) TableView: (UITableView *) TableView Heightforrowatindexpath: (Nsindexpath *) Indexpath {return
120; }//Cell check Event-(void) TableView: (UITableView *) TableView Didselectrowatindexpath: (Nsindexpath *) Indexpath {/** * To determine whether the current period is optional
In the state, if the selected state click to change to unchecked, if unchecked click is changed to selected state * * Goodsinfomodel *model = Infoarr[indexpath.row];

if (model.selectstate) {model.selectstate = NO; else {model.selectstate = YES;}//Flush integerForm//[_mytableview reloaddata];


Refreshes the current line [_mytableview Reloadrowsatindexpaths:@[indexpath] withrowanimation:uitableviewrowanimationautomatic];

[Self totalprice];

 }

2.8 Implement unit Gega, minus button agent
To import the Mycustomcelldelegate protocol in VIEWCONTROLLER.M first
@interface Viewcontroller () <UITableViewDataSource,UITableViewDelegate,MyCustomCellDelegate>
The implementation code is then as follows:

#pragma mark--implementation of the Add and Subtract button click Agent Event

/**
* Implementation plus minus button Click Agent Event
*
@param cell Current cell
* @param flag button logo, 11 for minus button, 12 for Plus Button
/

-(void) Btnclick: (UITableViewCell *) cell Andflag: (int) flag
{
 Nsindexpath *index = [_ Mytableview Indexpathforcell:cell];

Switch (flag) {case One
 :
 {/
 /subtraction
 ///Get to the current row data source content, change the data source content, refresh the table
 Goodsinfomodel *model = Infoarr[index.row];
 if (Model.goodsnum > 1)
 {
  model.goodsnum-;
 }
 }
 break;
 Case:

 {
 //Add
 Goodsinfomodel *model = Infoarr[index.row];

 Model.goodsnum + +;

 }

 break;

 Default: Break

 ;

}
Refresh Table
[_mytableview reloaddata];

Calculate the total price
[self totalprice];

}

2.9 Implementation of the total selection method

/**
* Full selection button Event
*
* @param sender All button/
-(void) Selectbtnclick: (UIButton *) sender
{
 // Determine whether selected, is changed to No, no change to be, changed the picture state
 Sender.tag =!sender.tag;
 if (Sender.tag)
 {
 [sender setimage:[uiimage imagenamed:@ check box-select. png] forstate:uicontrolstatenormal];

else{
 [sender setimage:[uiimage imagenamed:@ check box-unchecked. png] forstate:uicontrolstatenormal];
Change the state for
(int i=0; i<infoarr.count; i++)
{goodsinfomodel *model
 = [Infoarr objectatindex:i] in cell cell;
 model.selectstate = Sender.tag;

}
Calculated price
[self totalprice];
Refresh Table
[_mytableview reloaddata];

}

2.10 Calculate the Total price

#pragma mark-Calculate price
-(void) totalprice
{
 //traverse the entire data source, and then determine if the selected goods, the price (unit number * commodity quantity) for
 (int i =0; i< Infoarr.count; i++)
{
 Goodsinfomodel *model = [Infoarr objectatindex:i];
 if (model.selectstate)
 {
 Allprice = allprice + model.goodsnum *[model.goodsprice intvalue];
 }
}
Assign a value to the total price
_allpricelab.text = [NSString stringwithformat:@ "%.2f", Allprice];
NSLog (@ "%f", allprice);

Reset to 0 each time, because every time the whole cycle is counted
allprice = 0.0;
}

Short-time Handwriting: The code is more coarse, not completely sorted;

SOURCE Download: Http://xiazai.jb51.net/201612/yuanma/AndroidShoppingList (jb51.net). rar

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.