Additions and deletions of ios--products

Source: Internet
Author: User

Product additions and deletions part of the interface display



    • I'll take the theory and code to separate the way to write, in the code with comments to illustrate the steps

    • The main technology of the design

      • 1. Calculation of nine Gongge
      • 2. Custom Controls
      • 3. Lazy Loading
      • 4. Dictionary Turn model
Nine Gongge calculation
    • The value of the nine Gongge is not confined to the traditional 3x3 lattice, this calculation is able to extend to the calculation of NxN lattice.

    • Here the main point is to get the top left corner of the commodity control. For example, the No. 0 point of a product is (0.0)

    • Here, it is assumed that the width and height of each product are fixed (and this is true).

    • The x value of the frame for each product equals the width of the product plus the spacing multiplied by the column number.

    • Each column is equal to the width of the entire cabinet minus the width of the total product and divided by the number of items per column minus 1.

    • And Y has the same pattern.
      Code:
/************** Some common variables begin **************/    //Number of columns per rowNsuinteger Colsperrow =3;//Get the index of the current productNsuinteger index = Self.shopsView.subviews.count;//Product widthCGFloat SHOPW = -;//Product heightCGFloat Shoph = -;/************** Some of the commonly used variable end **************/    /************** calculate x value begin **************/    //Ask for a numberNsuinteger col = index% Colsperrow;//spacing between each columnCGFloat Xmargin = (Self.shopsview.frame.size.width-colsperrow * shopw)/(Colsperrow-1);//commodity xCGFloat shopx = (SHOPW + xmargin) * COL;/************** calculate x value End **************/    /************** calculate y value begin **************/    //Ask for travel numberNsuinteger row = Index/colsperrow;//spacing between each rowCGFloat Ymargin = -;//Commodity yCGFloat shopy = (shoph + ymargin) * ROW;/************** calculates the Y-value end **************/
Custom controls
    • 1. What child controls are required for analysis
    • 2. initWithFrame: add a child control to the method (the Init method automatically calls initWithFrame: method)
    • 3, layoutSubviews set the frame and other data in the method, that is, the Layout child control (Note: You must call the Super layoutSubviews method here)
    • 4. Override the Set method to assign a value to the child control
- (instancetype)initWithFrame:(CGRect)frame{     if (self = [super initWithFrame:frame]) {        ......        }    return self;}/***********************************************//** * 当前控件的frame发生改变的时候就会调用 * 这个方法专门用来布局子控件,设置子控件的frame */- (void)layoutSubviews{    // 一定要调用super方法    [super layoutSubviews];    ......}/***********************************************/- (void)setShop:(XMGShop *)shop{    _shop = shop;    ......}
Lazy Loading
    • Lazy loading is also called delayed loading, that is, when the first time it is loaded. Next time you want to use the time also do not have to load, judge on the OK. Lazy loading is widely used in iOS development and is a highly recommended way for Apple.

    • Characteristics:

      • 1, the first time to use the time before loading
      • 2, will only load once
    • The essence is to rewrite the Get method

    • code example

@property (nonatomicstrongNSArray *shops;//.....................................//- (NSArray *)shops{    ifnil) {_shops = 。。。。}    return _shops;}
Dictionary Turn model
    return _shops;}
    • Benefits:

      • 1, in the writing of the dictionary, it is easy to write key or something wrong, but Xcode will not be kind to error

      • 2, logically separate, in line with the MVC principle

      • 3. Easy to maintain code

      • 4. Improve reuse efficiency

      • 5 、。。。。

    • Steps:
      • 1. Create a new class that inherits from NSObject
      • 2. The required attributes are declared in. h and the get and set methods are automatically generated
      • 3. Provide an object method
      • 4. Provide a class method
      • 5, the object method is generally named: initwithdict:
      • 6, the class method is generally named: Class name Withdict:
      • 7. Take into account that everyone can use, all methods of self, do not write dead
    • code example:
//Shop.h#import <Foundation/Foundation.h>  @interface  Shop: nsobject @property(nonatomic,Strong)NSString*name;@property(nonatomic,Strong)NSString*icon;-(Instancetype) Initwithdict: (nsdictionary*) dict;+ (instancetype) Shopwithdict: (nsdictionary*) Dict;@end/*-------------------------------------------------------*///shop.m#import "Shop.h"  @implementation   Shop-(Instancetype) Initwithdict: (nsdictionary*) dict{if( Self=[SuperInit]) { Self. Name= dict[@"Name"]; Self. Icon= dict[@"icon"]; }return  Self;} + (Instancetype) Shopwithdict: (nsdictionary*) dict{return[[ SelfAlloc] initwithdict:dict];}@end
Some code shows
#import "ViewController.h" #import "LGShop.h" #import "LGShopView.h"  @interface viewcontroller ()//Commodity@property(nonatomic,Strong)Nsarray*shops;//Commodity cabinets@property(Weak,nonatomic)Iboutlet UIView*shopsview;//Add button@property(Weak,nonatomic)Iboutlet UIButton*addbutton;//Remove button@property(Weak,nonatomic)Iboutlet UIButton*removebutton;-(ibaction) add;-(ibaction) Remove;@end @implementation viewcontroller #pragma mark-lazy- (Nsarray*) shops{if(!_shops) {//Get plist file path    NSString*filepath = [[NSBundleMainbundle] pathforresource:@"Shops.plist"OfType:Nil];//Load by Path    Nsarray*shopsarray = [NsarrayArraywithcontentsoffile:filepath];//Create a temporary variable value to load the product    Nsmutablearray*temparray = [NsmutablearrayArraywithcapacity:shopsarray. Count];//Iterate through each dictionary and convert it to a model     for(nsdictionary*dict in Shopsarray) {lgshop *shop = [Lgshop shopwithdict:dict];    [Temparray Addobject:shop];    } _shops = [temparray copy]; }return_shops;} - (void) Viewdidload {[SuperViewdidload]; Self. RemoveButton. Enabled=NO;}#pragma mark-Call when you click Add Item- (ibaction) Add {//Nine calculation, the main calculation of each product X and y    //Number of columns per row    intColsperrow =4;//Commodity indexNsuinteger index = Self. Shopsview. Subviews. Count;//height and width of commodity    CGFloatShoph = -;CGFloatSHOPW = -;//wide height of commodity cabinets   //CGFloat SHOPVIEWH = self.shopsView.frame.size.height;    CGFloatSHOPVIEWW = Self. Shopsview. Bounds. Size. Width;//Seek x    //Column number    intcols = Index%colsperrow;//Column spacing    CGFloatMaginx = (SHOPVIEWW-SHOPW * colsperrow)/(Colsperrow-1);//x Value    CGFloatSHOPX = (SHOPW + maginx) * COLS;//Ask y    //Line number    unsigned Longrows = Index/colsperrow;//Line spacing equals column spacing    CGFloatMaginy = Maginx;//y Value    CGFloatShopy = -+ (Shoph + maginy) * rows;//Commodity parent controlLgshopview *shopview = [[Lgshopview alloc] init]; Shopview. Frame= CGRectMake (Shopx, Shopy, SHOPW, Shoph); [ Self. ShopsviewAddsubview:shopview];//Set dataShopview. Shop= Self. Shops[index];//When all the items in the warehouse have been added, you can no longer add     Self. RemoveButton. Enabled=YES; Self. AddButton. Enabled= ( Self. Shops. Count> Self. Shopsview. Subviews. Count);}#pragma mark-Call when you click Delete Item- (ibaction) Remove {//Remove the last item added[ Self. Shopsview. Subviews. LastobjectRemovefromsuperview];//cannot be removed after removal     Self. AddButton. Enabled=YES; Self. RemoveButton. Enabled= ( Self. Shopsview. Subviews. Count>0);}@end
    • 2
#import "LGShop.h"  @implementation lgshop //implementation of class methods and Object Methods+ (Instancetype) Shopwithdict: (nsdictionary*) dict{return[[ SelfAlloc] initwithdict:dict];} -(Instancetype) Initwithdict: (nsdictionary*) dict{if( Self= [SuperInit]) {//1. The method of honest transfer         Self. Name= dict[@"Name"]; Self. Icon= dict[@"icon"];/ *//2.KVC The following sentence is used KVC [self setvaluesforkeyswithdictionary:dict]; */}return  Self;}@end
    • 3
      "' OBJC
      #import "LGShopView.h"
Import "LGShop.h"

@interface Lgshopview ()

@property (nonatomic, weak) Uiimageview *imageview;

@property (nonatomic, weak) UILabel *namelabel;

@end

@implementation Lgshopview

pragma mark-Add child controls
    • (nonnull instancetype) initWithFrame: (CGRect) frame
      {
      if (self = [Super Initwithframe:frame]) {

      //添加图片空间UIImageView *shopImageView = [[UIImageView alloc] init];[self addSubview:shopImageView];self.imageView = shopImageView;//添加文字控件UILabel *nameLabel = [[UILabel alloc] init];nameLabel.textAlignment = NSTextAlignmentCenter;self.nameLabel = nameLabel;[self addSubview:nameLabel];}

      return self;
      }

Pragma mark-Set the child control's frame
    • (void) Layoutsubviews
      {
      [Super Layoutsubviews];

      CGFloat SHOPW = self.frame.size.width;
      CGFloat shoph = self.frame.size.height;

      Self.imageView.frame = CGRectMake (0, 0, SHOPW, SHOPW);

      Self.nameLabel.frame = CGRectMake (0, SHOPW, SHOPW, SHOPH-SHOPW);

}

Override the Set method to assign a value to a child control
-(void) Setshop: (Lgshop *) Shop
{
_shop =shop;
Self.imageView.image = [UIImage ImageNamed:shop.icon];
Self.nameLabel.text = Shop.name;
}

@end
"'
-The code repository has all the code:
-Https://github.com/LGLee/addAndRemoveShop

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Additions and deletions of ios--products

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.