您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 中 View 之間傳值的幾種常見做法

編輯:iOS 開發綜合

在多個畫面之間切換時,如何把資料從一個 View 傳到另一個 View,是 iOS 開發的基本功。以下整理三種常見的傳值方式,並附上範例。

一、透過 NSUserDefaults 傳值

這種方式只適合傳遞少量資料。例如要傳一個 float 值:

設定時:

[[NSUserDefaults standardUserDefaults] setFloat:fValue forKey:@"float"];

取值時:

[[NSUserDefaults standardUserDefaults] floatForKey:@"float"];

二、透過 NSNotificationCenter 傳值

發送端在觸碰結束時,把座標打包成字典,透過通知中心拋出:

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch * touch = [touches anyObject];
    CGPoint point = [touch locationInView:self];
    CGRect roundRect = [self rectNeedRefreshFromThisPoint:point];
    mLastPoint = CGPointMake(-1, -1);

    NSLog(@"%s: point(%f,%f)", __FUNCTION__, point.x, point.y);

    [self addToCurrentLineWithPoint:point.x y:point.y];
    [self endLine];
    [self setNeedsDisplayInRect:roundRect];

    NSNumber *pointX = [NSNumber numberWithFloat:point.x];
    NSNumber *pointY = [NSNumber numberWithFloat:point.y];
    NSDictionary *pointDict = [NSDictionary dictionaryWithObjectsAndKeys:
                               pointX, @"pointX", pointY, @"pointY", nil];
    [[NSNotificationCenter defaultCenter]
        postNotificationName:@"passTouchedEndPointMsg"
                      object:self
                    userInfo:pointDict];
}

接收端先註冊觀察者:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(getTouchedPoint:)
                                             name:@"passTouchedEndPointMsg"
                                           object:nil];

收到通知後取出資料:

- (void) getTouchedPoint:(NSNotification *)noti
{
    NSDictionary *pointDict = [noti userInfo];
    touchedEndPointX = [[pointDict objectForKey:@"pointX"] floatValue];
    touchedEndPointY = [[pointDict objectForKey:@"pointY"] floatValue];
    NSLog(@"%f:%f", touchedEndPointX, touchedEndPointY);
}

使用通知傳參數時有幾個重點:object 代表發送者;發送端可把要傳的參數放進 userInfo,且必須是 NSDictionary 類型;接收端則用 [notification userInfo] 取得這份字典。

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