您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

iOS UI 開發基本功:懶加載與 xib 的實際用法

編輯:iOS 相關教學

一、懶加載:什麼時候建立,什麼時候才該建立

懶加載也叫延遲加載,核心思想只有一句:等到真正被使用的時候才去建立物件。這樣做啟動更快、記憶體佔用更低。實作上就是重寫 getter 方法。

有個前提務必記住:getter 裡一定要先判斷是否已經存在,不存在才走初始化。

它帶來的好處有兩點:

(1)不必把所有建立物件的程式碼一股腦塞進 viewDidLoad,可讀性更好。
(2)每個控制項在自己的 getter 裡負責自己的例化,彼此獨立,耦合度低。

下面用一個圖片瀏覽器把這個模式寫完整。

YYViewController.m:


//
//  YYViewController.m
//  03-圖片浏覽器初步
//
//  Created by apple on 14-5-21.
//  Copyright (c) 2014年 itcase. All rights reserved.
//

#import "YYViewController.h"

#define POTOIMGW    200
#define POTOIMGH    300
#define POTOIMGX    60
#define  POTOIMGY    50

@interface YYViewController ()

@property(nonatomic,strong)UILabel *firstlab;
@property(nonatomic,strong)UILabel *lastlab;
@property(nonatomic,strong)UIImageView *icon;
@property(nonatomic,strong)UIButton *leftbtn;
@property(nonatomic,strong)UIButton *rightbtn;
@property(nonatomic,strong)NSArray *array;
@property(nonatomic ,assign)int i;
-(void)change;
@end


@implementation YYViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self change];
}

-(void)change
{
    [self.firstlab setText:[NSString stringWithFormat:@"%d/5",self.i+1]];
    //先get再set
    self.icon.image=[UIImage imageNamed:self.array[self.i][@"name"]];
    self.lastlab.text=self.array[self.i][@"desc"];
    self.leftbtn.enabled=(self.i!=0);
    self.rightbtn.enabled=(self.i!=4);
}

//延遲加載
/**1.圖片的序號標簽*/
-(UILabel *)firstlab
{
    //判斷是否已經有了,若沒有,則進行實例化
    if (!_firstlab) {
        _firstlab=[[UILabel alloc]initWithFrame:CGRectMake(20, 10, 300, 30)];
        [_firstlab setTextAlignment:NSTextAlignmentCenter];
        [self.view addSubview:_firstlab];
    }
    return _firstlab;
}

/**2.圖片控件的延遲加載*/
-(UIImageView *)icon
{
    if (!_icon) {
        _icon=[[UIImageView alloc]initWithFrame:CGRectMake(POTOIMGX, POTOIMGY, POTOIMGW, POTOIMGH)];
        UIImage *image=[UIImage imageNamed:@"biaoqingdi"];
        _icon.image=image;
        [self.view addSubview:_icon];
    }
    return _icon;
}

/**3.描述控件的延遲加載*/
-(UILabel *)lastlab
{
    if (!_lastlab) {
        _lastlab=[[UILabel alloc]initWithFrame:CGRectMake(20, 400, 300, 30)];
        [_lastlab setTextAlignment:NSTextAlignmentCenter];
        [self.view addSubview:_lastlab];
    }
    return _lastlab;
}

/**4.左鍵按鈕的延遲加載*/
-(UIButton *)leftbtn
{
    if (!_leftbtn) {
        _leftbtn=[UIButton buttonWithType:UIButtonTypeCustom];
        _leftbtn.frame=CGRectMake(0, self.view.center.y, 40, 40);
        [_leftbtn setBackgroundImage:[UIImage imageNamed:@"left_normal"] forState:UIControlStateNormal];
        [_leftbtn setBackgroundImage:[UIImage imageNamed:@"left_highlighted"] forState:UIControlStateHighlighted];
        [self.view addSubview:_leftbtn];
        [_leftbtn addTarget:self action:@selector(leftclick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _leftbtn;
}

/**5.右鍵按鈕的延遲加載*/
-(UIButton *)rightbtn
{
    if (!_rightbtn) {
        _rightbtn=[UIButton buttonWithType:UIButtonTypeCustom];
        _rightbtn.frame=CGRectMake(POTOIMGX+POTOIMGW+10, self.view.center.y, 40, 40);
        [_rightbtn setBackgroundImage:[UIImage imageNamed:@"right_normal"] forState:UIControlStateNormal];
        [_rightbtn setBackgroundImage:[UIImage imageNamed:@"right_highlighted"] forState:UIControlStateHighlighted];
        [self.view addSubview:_rightbtn];
        [_rightbtn addTarget:self action:@selector(rightclick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightbtn;
}

//array的get方法
-(NSArray *)array
{
    if (_array==nil) {
        NSString *path=[[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"];
        _array=[[NSArray alloc]initWithContentsOfFile:path];
    }
    return _array;
}

-(void)rightclick:(UIButton *)btn
{
    self.i++;
    [self change];
}

-(void)leftclick:(UIButton *)btn
{
    self.i--;
    [self change];
}

@end

注意 change 方法裡那句註解「先 get 再 set」:正是因為呼叫了 self.firstlab,getter 才會被觸發,控制項才會第一次被建立並加入視圖。這是懶加載最容易被忽略的一環。

二、xib 入門

1. xib 與 storyboard 的分界

兩者的共同點:都用來描述軟體界面,都用 Interface Builder 編輯。

差別在粒度。xib 是輕量級的,用來描述局部的 UI 畫面;storyboard 是重量級的,用來描述整個 App 的多個畫面,還能呈現畫面之間的跳轉關係。

2. 建立並設定一個 xib

新建 xib 檔,命名為 appxib.xib:

依需求把 view 改成自由布局:

設定 view 的尺寸等參數:

調整內部控制項的佈局:

完成的單個 view:

3. 載入 xib 並用 tag 取值

YYViewController.m:


#import "YYViewController.h"
#import "YYapp.h"

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


@implementation YYViewController

//1.加載數據信息
-(NSArray *)app
{
    if (!_app) {
        NSString *path=[[NSBundle mainBundle]pathForResource:@"app.plist" ofType:nil];
        NSArray *temparray=[NSArray arrayWithContentsOfFile:path];
       
        //字典轉模型
        NSMutableArray *arrayM=[NSMutableArray array];
        for (NSDictionary *dict in temparray) {
            [arrayM addObject:[YYapp appWithDict:dict]];
        }
        _app=arrayM;
    }
    return _app;
}

//創建界面原型
- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"%d",self.app.count);
   
    //九宮格布局
    int totalloc=3;
    CGFloat appviewW=80;
    CGFloat appviewH=90;
    CGFloat margin=(self.view.frame.size.width-totalloc*appviewW)/(totalloc+1);
   
    int count=self.app.count;
    for (int i=0; i<count; i++) {
        int row=i/totalloc;
        int loc=i%totalloc;
        CGFloat appviewX=margin + (margin +appviewW)*loc;
        CGFloat appviewY=margin + (margin +appviewH)*row;
        YYapp *app=self.app[i];
       
        //拿出xib視圖
        NSArray *apparray= [[NSBundle mainBundle]loadNibNamed:@"appxib" owner:nil options:nil];
        UIView *appview=[apparray firstObject];
        //加載視圖
        appview.frame=CGRectMake(appviewX, appviewY, appviewW, appviewH);
       
        UIImageView *appviewImg=(UIImageView *)[appview viewWithTag:1];
        appviewImg.image=app.image;
       
        UILabel *appviewlab=(UILabel *)[appview viewWithTag:2];
        appviewlab.text=app.name;
       
        UIButton *appviewbtn=(UIButton *)[appview viewWithTag:3];
        [appviewbtn addTarget:self action:@selector(appviewbtnClick:) forControlEvents:UIControlEventTouchUpInside];
        appviewbtn.tag=i;
       
        [self.view addSubview:appview];
    }
}

/**按鈕的點擊事件*/
-(void)appviewbtnClick:(UIButton *)btn
{
    YYapp *apps=self.app[btn.tag];
    UILabel *showlab=[[UILabel alloc]initWithFrame:CGRectMake(60, 450, 200, 20)];
    [showlab setText:[NSString stringWithFormat: @"%@下載成功",apps.name]];
    [showlab setBackgroundColor:[UIColor lightGrayColor]];
    [self.view addSubview:showlab];
    showlab.alpha=1.0;
   
    //簡單的動畫效果
    [UIView animateWithDuration:2.0 animations:^{
        showlab.alpha=0;
    } completion:^(BOOL finished) {
        [showlab removeFromSuperview];
    }];
}

@end

執行結果:

這裡有個實用小技巧:appviewbtn.tag=i 這行會覆蓋掉 xib 裡設定的 tag,用來記錄索引,點擊時就能反查是哪一筆資料。九宮格的座標計算則是純數學:先算出邊距,再用商與餘數推出行列位置。

4. 給 xib 連線

新建一個對應的 view 類,繼承自 UIView:

在 xib 右上角把 File's Owner 或 view 關聯到這個類:

拖一拖,把控制項連線到程式碼屬性:

注意:使用時記得把預設的 weak 改成 strong,否則控制項會被提前釋放。

連線後的主控制器:


#import "YYViewController.h"
#import "YYapp.h"
#import "YYappview.h"

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


@implementation YYViewController

//1.加載數據信息
-(NSArray *)app
{
    if (!_app) {
        NSString *path=[[NSBundle mainBundle]pathForResource:@"app.plist" ofType:nil];
        NSArray *temparray=[NSArray arrayWithContentsOfFile:path];
       
        //字典轉模型
        NSMutableArray *arrayM=[NSMutableArray array];
        for (NSDictionary *dict in temparray) {
            [arrayM addObject:[YYapp appWithDict:dict]];
        }
        _app=arrayM;
    }
    return _app;
}

//創建界面原型
- (void)viewDidLoad
{
    [super viewDidLoad];
   
    //九宮格布局
    int totalloc=3;
    CGFloat appviewW=80;
    CGFloat appviewH=90;
    CGFloat margin=(self.view.frame.size.width-totalloc*appviewW)/(totalloc+1);
   
    int count=self.app.count;
    for (int i=0; i<count; i++) {
        int row=i/totalloc;
        int loc=i%totalloc;
        CGFloat appviewX=margin + (margin +appviewW)*loc;
        CGFloat appviewY=margin + (margin +appviewH)*row;
        YYapp *app=self.app[i];
       
        //拿出xib視圖
        NSArray *apparray= [[NSBundle mainBundle]loadNibNamed:@"appxib" owner:nil options:nil];
       
        //注意這裡的類型名
        YYappview *appview=[apparray firstObject];
       
        appview.frame=CGRectMake(appviewX, appviewY, appviewW, appviewH);
        [self.view addSubview:appview];
       
        appview.appimg.image=app.image;
        appview.applab.text=app.name;
        appview.appbtn.tag=i;
        [appview.appbtn addTarget:self action:@selector(appviewbtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
}

/**按鈕的點擊事件*/
-(void)appviewbtnClick:(UIButton *)btn
{
    YYapp *apps=self.app[btn.tag];
    UILabel *showlab=[[UILabel alloc]initWithFrame:CGRectMake(60, 450, 200, 20)];
    [showlab setText:[NSString stringWithFormat: @"%@下載成功",apps.name]];
    [showlab setBackgroundColor:[UIColor lightGrayColor]];
    [self.view addSubview:showlab];
    showlab.alpha=1.0;
    [UIView animateWithDuration:2.0 animations:^{
        showlab.alpha=0;
    } completion:^(BOOL finished) {
        [showlab removeFromSuperview];
    }];
}

@end

YYappview.h(已完成連線):

#import <UIKit/UIKit.h>

@interface YYappview : UIView
@property (strong, nonatomic) IBOutlet UIImageView *appimg;
@property (strong, nonatomic) IBOutlet UILabel *applab;
@property (strong, nonatomic) IBOutlet UIButton *appbtn;
@end

對比兩版可以清楚看到差異:用 tag 取值時,控制器需要知道 1、2、3 分別對應哪個控制項;連線之後,取值變成 appview.appimg、appview.applab,語義自明,也不必再記數字。這就是為什麼在正式專案裡,xib 一定要配一個專屬的 view 類。

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