你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> 詳解iOS運用UI開辟中的九宮格坐標盤算與字典轉換模子

詳解iOS運用UI開辟中的九宮格坐標盤算與字典轉換模子

編輯:IOS開發綜合

九宮格坐標盤算

1、請求

完成上面的結構

20161790120507.png (624×340)

2、剖析

尋覓右邊的紀律,每個uiview的x坐標和y坐標。

https://www.ios5.online/ios/UploadFiles_8070/201703/2017031615464299.png (631×381)

3、完成思緒

(1)明白每塊用得是甚麼view

(2)明白每一個view之間的父子關系,每一個視圖都只要一個父視圖,具有許多的子視圖。

(3)可以先測驗考試逐一的添加格子,最初斟酌應用for輪回,完成一切uiview的創立

(4)加載app數據,依據數據長度創立對應個數的格子

(5)添加格子外部的子控件

(6)給外部的子控件拆卸數據

4、代碼示例

//
//  YYViewController.m
//  九宮格演習
//
//  Created by 孔醫己 on 14-5-22.
//  Copyright (c) 2014年 itcast. All rights reserved.
//

#import "YYViewController.h"

@interface YYViewController ()
@property(nonatomic,strong)NSArray *apps;
@end


@implementation YYViewController
//1.加載數據
- (NSArray *)apps
{
    if (!_apps) {
        NSString *path=[[NSBundle mainBundle]pathForResource:@"app.plist" ofType:nil];
        _apps=[NSArray arrayWithContentsOfFile:path];
    }
    return _apps;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"%d",self.apps.count);
   
    //2.完成結構設計
   
    //三列
    int totalloc=3;
    CGFloat appvieww=80;
    CGFloat appviewh=90;
   
    CGFloat margin=(self.view.frame.size.width-totalloc*appvieww)/(totalloc+1);
    int count=self.apps.count;
    for (int i=0; i<count; i++) {
        int row=i/totalloc;//行號
        //1/3=0,2/3=0,3/3=1;
        int loc=i%totalloc;//列號
       
        CGFloat appviewx=margin+(margin+appvieww)*loc;
        CGFloat appviewy=margin+(margin+appviewh)*row;
       
       
        //創立uiview控件
        UIView *appview=[[UIView alloc]initWithFrame:CGRectMake(appviewx, appviewy, appvieww, appviewh)];
        //[appview setBackgroundColor:[UIColor purpleColor]];
        [self.view addSubview:appview];
       
       
        //創立uiview控件中的子視圖
        UIImageView *appimageview=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 80, 50)];
        UIImage *appimage=[UIImage imageNamed:self.apps[i][@"icon"]];
        appimageview.image=appimage;
        [appimageview setContentMode:UIViewContentModeScaleaspectFit];
       // NSLog(@"%@",self.apps[i][@"icon"]);
        [appview addSubview:appimageview];
       
        //創立文本標簽
        UILabel *applable=[[UILabel alloc]initWithFrame:CGRectMake(0, 50, 80, 20)];
        [applable setText:self.apps[i][@"name"]];
        [applable setTextAlignment:NSTextAlignmentCenter];
        [applable setFont:[UIFont systemFontOfSize:12.0]];
        [appview addSubview:applable];
       
        //創立按鈕
        UIButton *appbtn=[UIButton buttonWithType:UIButtonTypeCustom];
        appbtn.frame= CGRectMake(10, 70, 60, 20);
        [appbtn setBackgroundImage:[UIImage imageNamed:@"buttongreen"] forState:UIControlStateNormal];
        [appbtn setBackgroundImage:[UIImage imageNamed:@"buttongreen_highlighted"] forState:UIControlStateHighlighted];
        [appbtn setTitle:@"下載" forState:UIControlStateNormal];
        appbtn.titleLabel.font=[UIFont systemFontOfSize:12.0];
        [appview addSubview:appbtn];
       
        [appbtn addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
    }

}

-(void)click
{
    //動畫標簽
    UILabel *animalab=[[UILabel alloc]initWithFrame:CGRectMake(self.view.center.x-100, self.view.center.y+20, 200, 40)];
    [animalab setText:@"下載勝利"];
    animalab.font=[UIFont systemFontOfSize:12.0];
    [animalab setBackgroundColor:[UIColor brownColor]];
    [animalab setAlpha:0];
    [self.view addSubview:animalab];
   
//    [UIView beginAnimations:Nil context:Nil];
//    [animalab setAlpha:1];
//    [UIView setAnimationDuration:4.0];
//    [UIView commitAnimations];
   
    //履行完以後,還得把這給刪除,推舉應用block動畫
   
    [UIView animateWithDuration:4.0 animations:^{
    [animalab setAlpha:1];
    } completion:^(BOOL finished) {
        //[self.view re];
    }];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end

履行後果:

https://www.ios5.online/ios/UploadFiles_8070/201703/2017031615464258.png (640×960)

字典轉模子

1、能完勝利能的“成績代碼”

1.從plist中加載的數據

https://www.ios5.online/ios/UploadFiles_8070/201703/2017031615464296.png (799×290)

2.完成的代碼

//
//  LFViewController.m
//  03-運用治理
//
//  Created by apple on 14-5-22.
//  Copyright (c) 2014年 heima. All rights reserved.
//

#import "LFViewController.h"

@interface LFViewController ()
@property (nonatomic, strong) NSArray *appList;
@end

@implementation LFViewController

- (NSArray *)appList
{
    if (!_appList) {

        // 1. 從mainBundle加載
        NSBundle *bundle = [NSBundle mainBundle];
        NSString *path = [bundle pathForResource:@"app.plist" ofType:nil];
        _appList = [NSArray arrayWithContentsOfFile:path];
       
        NSLog(@"%@", _appList);
    }
    return _appList;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
   
    // 總共有3列
    int totalCol = 3;
    CGFloat viewW = 80;
    CGFloat viewH = 90;
   
    CGFloat marginX = (self.view.bounds.size.width - totalCol * viewW) / (totalCol + 1);
    CGFloat marginY = 10;
    CGFloat startY = 20;
   
    for (int i = 0; i < self.appList.count; i++) {

        int row = i / totalCol;
        int col = i % totalCol;
       
        CGFloat x = marginX + (viewW + marginX) * col;
        CGFloat y = startY + marginY + (viewH + marginY) * row;
       
        UIView *appView = [[UIView alloc] initWithFrame:CGRectMake(x, y, viewW, viewH)];
     
        [self.view addSubview:appView];
       
        // 創立appView外部的細節
        // 0> 讀取數組中的字典
        NSDictionary *dict = self.appList[i];
       
        // 1> UIImageView
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, viewW, 50)];
        imageView.image = [UIImage imageNamed:dict[@"icon"]];
        imageView.contentMode = UIViewContentModeScaleaspectFit;
        [appView addSubview:imageView];
       
        // 2> UILabel
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, imageView.bounds.size.height, viewW, 20)];
        // 設置文字
        label.text = dict[@"name"];
        label.font = [UIFont systemFontOfSize:12.0];
        label.textAlignment = NSTextAlignmentCenter;
       
        [appView addSubview:label];
       
        // 3> UIButton
        // UIButtonTypeCustom和[[UIButton alloc] init]是等價的
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(15, 70, viewW - 30, 20);
       
        [button setTitle:@"下載" forState:UIControlStateNormal];
        // *** 不克不及應用以下代碼直接設置title
//        button.titleLabel.text = @"下載";
        // @property中readonly表現不許可修正對象的指針地址,然則可以修正對象的屬性
        button.titleLabel.font= [UIFont systemFontOfSize:14.0];
       
        [button setBackgroundImage:[UIImage imageNamed:@"buttongreen"] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:@"buttongreen_highlighted"] forState:UIControlStateHighlighted];
       
        [appView addSubview:button];
    }
}

@end

3.完成後果

https://www.ios5.online/ios/UploadFiles_8070/201703/2017031615464228.png (322×499)

4.代碼成績

在上述代碼的第62,69行,我們是直接經由過程字典的鍵名獲得plist中的數據信息,在viewController中須要直接和數據打交道,假如須要屢次應用能夠會由於不當心把鍵名寫錯,而法式其實不報錯。鑒於此,可以斟酌把字典數據轉換成一個模子,把數據封裝到一個模子中去,讓viewController不再直接和數據打交道,而是和模子交互。

普通情形下,設置數據和掏出數據都應用“字符串類型的key”,編寫這些key時,編纂器沒有智能提醒,須要手敲。如:

dict[@"name"] = @"Jack";

NSString *name = dict[@"name"];

手敲字符串key,key輕易寫錯

Key假如寫錯了,編譯器不會有任何正告和報錯,形成設錯數據或許取錯數據

2、字典轉模子

1.字典轉模子引見

表示圖:

https://www.ios5.online/ios/UploadFiles_8070/201703/2017031615464262.png (683×340)

字典轉模子的利益:

(1)下降代碼的耦合度

(2)一切字典轉模子部門的代碼同一集中在一處處置,下降代碼失足的概率

(3)在法式中直接應用模子的屬性操作,進步編碼效力

(4)挪用方不消關懷模子外部的任何處置細節

字典轉模子的留意點:

模子應當供給一個可以傳入字典參數的結構辦法

- (instancetype)initWithDict:(NSDictionary *)dict;

+ (instancetype)xxxWithDict:(NSDictionary *)dict;

提醒:在模子中公道地應用只讀屬性,可以進一步下降代碼的耦合度。

 

 2.代碼示例(一)

新建一個類,用來作為數據模子

viewController.m文件代碼(字典轉模子)
#import "LFViewController.h"
#import "LFAppInfo.h"

@interface LFViewController ()
@property (nonatomic, strong) NSArray *appList;
@end

@implementation LFViewController

// 字典轉模子
- (NSArray *)appList
{
    if (!_appList) {
        // 1. 從mainBundle加載
        NSBundle *bundle = [NSBundle mainBundle];
        NSString *path = [bundle pathForResource:@"app.plist" ofType:nil];
//        _appList = [NSArray arrayWithContentsOfFile:path];
       
        NSArray *array = [NSArray arrayWithContentsOfFile:path];
        // 將數組轉換成模子,意味著self.appList中存儲的是LFAppInfo對象
        // 1. 遍歷數組,將數組中的字典順次轉換成AppInfo對象,添加到一個暫時數組
        // 2. self.appList = 暫時數組

        NSMutableArray *arrayM = [NSMutableArray array];
        for (NSDictionary *dict in array) {
           //用字典來實例化對象的工場辦法
            [arrayM addObject:[LFAppInfo appInfoWithDict:dict]];
        }
       
        _appList = arrayM;
    }
    return _appList;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
   
    // 總共有3列
    int totalCol = 3;
    CGFloat viewW = 80;
    CGFloat viewH = 90;
   
    CGFloat marginX = (self.view.bounds.size.width - totalCol * viewW) / (totalCol + 1);
    CGFloat marginY = 10;
    CGFloat startY = 20;
   
    for (int i = 0; i < self.appList.count; i++) {

        int row = i / totalCol;
        int col = i % totalCol;
       
        CGFloat x = marginX + (viewW + marginX) * col;
        CGFloat y = startY + marginY + (viewH + marginY) * row;
       
        UIView *appView = [[UIView alloc] initWithFrame:CGRectMake(x, y, viewW, viewH)];
       
        [self.view addSubview:appView];
       
        // 創立appView外部的細節
        // 0> 讀取數組中的AppInfo
//        NSDictionary *dict = self.appList[i];
        LFAppInfo *appInfo = self.appList[i];
       
        // 1> UIImageView
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, viewW, 50)];
        imageView.image = appInfo.image;
        imageView.contentMode = UIViewContentModeScaleaspectFit;
       
        [appView addSubview:imageView];
       
        // 2> UILabel
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, imageView.bounds.size.height, viewW, 20)];
        // 設置文字
        label.text = appInfo.name;
        label.font = [UIFont systemFontOfSize:12.0];
        label.textAlignment = NSTextAlignmentCenter;
       
        [appView addSubview:label];
       
        // 3> UIButton
        // UIButtonTypeCustom和[[UIButton alloc] init]是等價的
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(15, 70, viewW - 30, 20);
       
        [button setTitle:@"下載" forState:UIControlStateNormal];
        button.titleLabel.font= [UIFont systemFontOfSize:14.0];
       
        [button setBackgroundImage:[UIImage imageNamed:@"buttongreen"] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:@"buttongreen_highlighted"] forState:UIControlStateHighlighted];
       
        [appView addSubview:button];
        button.tag = i;
       
        [button addTarget:self action:@selector(downloadClick:) forControlEvents:UIControlEventTouchUpInside];
    }
}

- (void)downloadClick:(UIButton *)button
{
    NSLog(@"%d", button.tag);
    // 實例化一個UILabel顯示在視圖上,提醒用戶下載完成
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(80, 400, 160, 40)];
    label.textAlignment = NSTextAlignmentCenter;
    label.backgroundColor = [UIColor lightGrayColor];
   
    LFAppInfo *appInfo = self.appList[button.tag];
    label.text = [NSString stringWithFormat:@"下載%@完成", appInfo.name];
    label.font = [UIFont systemFontOfSize:13.0];
    label.alpha = 1.0;
    [self.view addSubview:label];
   
    // 動畫後果
    // 動畫後果完成以後,將Label從視圖中刪除
    // 首尾式動畫,只能做動畫,要處置完成後的操作不便利
//    [UIView beginAnimations:nil context:nil];
//    [UIView setAnimationDuration:1.0];
//    label.alpha = 1.0;
//    [UIView commitAnimations];

    // block動畫比首尾式動畫簡略,並且可以或許掌握動畫停止後的操作
    // 在IOS中,根本都應用首尾式動畫
    [UIView animateWithDuration:2.0 animations:^{
        label.alpha = 0.0;
    } completion:^(BOOL finished) {
        // 刪除label
        [label removeFromSuperview];
    }];
}

@end

模子.h文件代碼

#import <Foundation/Foundation.h>

@interface LFAppInfo : NSObject

// 運用法式稱號
@property (nonatomic, copy) NSString *name;
// 運用法式圖標稱號
@property (nonatomic, copy) NSString *icon;

// 圖象
// 界說屬性時,會生成getter&setter辦法,還會生成一個帶下劃線的成員變量
// 假如是readonly屬性,只會生成getter辦法,同時沒有成員變量
@property (nonatomic, strong, readonly) UIImage *image;

// instancetype會讓編譯器檢討實例化對象的精確類型
// instancetype只能用於前往類型,不克不及當作參數應用

- (instancetype)initWithDict:(NSDictionary *)dict;
/** 工場辦法 */
+ (instancetype)appInfoWithDict:(NSDictionary *)dict;

@end

模子.m文件數據處置代碼

#import "LFAppInfo.h"

@interface LFAppInfo()
{
    UIImage *_imageABC;
}
@end


@implementation LFAppInfo

- (instancetype)initWithDict:(NSDictionary *)dict
{
    self = [super init];
    if (self) {
        self.name = dict[@"name"];
        self.icon = dict[@"icon"];
    }
    return self;
}

+ (instancetype)appInfoWithDict:(NSDictionary *)dict
{
    return [[self alloc] initWithDict:dict];
}

- (UIImage *)image
{
    if (!_imageABC) {
        _imageABC = [UIImage imageNamed:self.icon];
    }
    return _imageABC;
}

@end

3.代碼示例(二)

數據信息:plist文件

https://www.ios5.online/ios/UploadFiles_8070/201703/2017031615464233.png (763×667)

字典轉模子(初步)

模子.h文件

#import <Foundation/Foundation.h>

@interface LFQuestion : NSObject

@property (nonatomic, copy) NSString *answer;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *icon;
@property (nonatomic, strong) NSArray *options;

@property (nonatomic, strong) UIImage *image;

/** 用字典實例化對象的成員辦法 */
- (instancetype)initWithDict:(NSDictionary *)dict;
/** 用字典實例化對象的類辦法,又稱工場辦法 */
+ (instancetype)questionWithDict:(NSDictionary *)dict;
@end

模子.m文件

#import "LFQuestion.h"

@implementation LFQuestion

+ (instancetype)questionWithDict:(NSDictionary *)dict
{
    return [[self alloc] initWithDict:dict];
}

- (instancetype)initWithDict:(NSDictionary *)dict
{
    self = [super init];
    if (self) {
        self.answer = dict[@"answer"];
        self.icon = dict[@"icon"];
        self.title = dict[@"title"];
        self.options = dict[@"options"];

        [self setValuesForKeysWithDictionary:dict];
    }
    return self;
}

viewController.m文件中的數據處置

- (NSArray *)questions
{
    if (!_questions) {
   
        NSArray *array = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"questions.plist" ofType:nil]];
       
        NSMutableArray *arrayM = [NSMutableArray array];
       
        for (NSDictionary *dict in array) {
            [arrayM addObject:[LFQuestion questionWithDict:dict]];
        }
        _questions=arrayM;
    }
    return _questions;
}

字典轉模子(優化)

下面代碼可以做進一步的優化,從plist文件中讀取數據是可以交給模子行止理的,優化子女碼以下:

模子.h文件

#import <Foundation/Foundation.h>

@interface LFQuestion : NSObject

@property (nonatomic, copy) NSString *answer;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *icon;
@property (nonatomic, strong) NSArray *options;

@property (nonatomic, strong) UIImage *image;

/** 用字典實例化對象的成員辦法 */
- (instancetype)initWithDict:(NSDictionary *)dict;
/** 用字典實例化對象的類辦法,又稱工場辦法 */
+ (instancetype)questionWithDict:(NSDictionary *)dict;

/** 從plist加載對象數組 */
+ (NSArray *)questions;

@end

模子.m文件

#import "LFQuestion.h"

@implementation LFQuestion

+ (instancetype)questionWithDict:(NSDictionary *)dict
{
    return [[self alloc] initWithDict:dict];
}

- (instancetype)initWithDict:(NSDictionary *)dict
{
    self = [super init];
    if (self) {
        self.answer = dict[@"answer"];
        self.icon = dict[@"icon"];
        self.title = dict[@"title"];
        self.options = dict[@"options"];
       
        [self setValuesForKeysWithDictionary:dict];
    }
    return self;
}


+ (NSArray *)questions
{
    NSArray *array = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"questions.plist" ofType:nil]];
   
    NSMutableArray *arrayM = [NSMutableArray array];
   
    for (NSDictionary *dict in array) {
        [arrayM addObject:[LFQuestion questionWithDict:dict]];
    }
   
    return arrayM;
}
@end

viewController.m文件中的數據處置代碼部門

- (NSArray *)questions
{
    if (!_questions) {
        _questions = [LFQuestion questions];
    }
    return _questions;
}

彌補內容:(KVC)的應用

(1)在模子外部的數據處置部門,可使用鍵值編碼來停止處置

- (instancetype)initWithDict:(NSDictionary *)dict
{
    self = [super init];
    if (self) {
//        self.answer = dict[@"answer"];
//        self.icon = dict[@"icon"];
//        self.title = dict[@"title"];
//        self.options = dict[@"options"];
       
        // KVC (key value coding)鍵值編碼
        // cocoa 的年夜招,許可直接修正對象的屬性值
        // 第一個參數是字典的數值
        // 第二個參數是類的屬性
        [self setValue:dict[@"answer"] forKeyPath:@"answer"];
        [self setValue:dict[@"icon"] forKeyPath:@"icon"];
        [self setValue:dict[@"title"] forKeyPath:@"title"];
        [self setValue:dict[@"options"] forKeyPath:@"options"];
    }
    return self;
}

(2)setValuesForKeys的應用

上述數據操作細節,可以直接經由過程setValuesForKeys辦法來完成。

- (instancetype)initWithDict:(NSDictionary *)dict
{
    self = [super init];
    if (self) {
        // 應用setValuesForKeys請求類的屬性必需在字典中存在,可以比字典中的鍵值多,然則不克不及少。
        [self setValuesForKeysWithDictionary:dict];
    }
    return self;
}

3、彌補解釋

1.readonly屬性

 (1)@property中readonly表現不許可修正對象的指針地址,然則可以修正對象的屬性。

 (2)平日應用@property症結字界說屬性時,會生成getter&setter辦法,還會生成一個帶下劃線的成員變量。

 (3)假如是readonly屬性,只會生成getter辦法,不會生成帶下劃線的成員變量.

2.instancetype類型

(1)instancetype會讓編譯器檢討實例化對象的精確類型
(2)instancetype只能用於前往類型,不克不及當作參數應用

3.instancetype & id的比擬

(1) instancetype在類型表現上,跟id一樣,可以表現任何對象類型

(2) instancetype只能用在前往值類型上,不克不及像id一樣用在參數類型上

(3) instancetype比id多一個利益:編譯器會檢測instancetype的真實類型

【詳解iOS運用UI開辟中的九宮格坐標盤算與字典轉換模子】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved